-
-
Save ahmetgungor/e2e8152ff062bc47487ea06b8285d0b7 to your computer and use it in GitHub Desktop.
Javascript number mask
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const mask = (res = "", regex) => { | |
if (res.replace(/\D+/gim, "").length == 0) return ""; | |
if (res.replace(/\D+/gim, "").length > regex.replace(/\D+/gim, "").length) | |
return res.slice(0, regex.replace(/\[|\]/gim, "").length); | |
let regexNumber = regex.match(/\d+/gim, ""), //sadece sayılar | |
totalLen = res.match(/\d+/gim, "").join("").length, //gelen değerin uzunluğu | |
number = res.match(/\d+/gim, "").join("") + new Array(regexNumber.join("").length - totalLen).fill("_").join(""), | |
len = 0, | |
rlen = 0; | |
let match = regex.replace(/\[\d+\]/gim, (m, k) => m.replace(/\[\d+\]/gim, "$" + rlen++)); | |
regexNumber.map((i, k) => { | |
match = match.replace("$" + k, number.slice(len, len + i.length)); | |
len = len + i.length; | |
}); | |
return match.replace(/[\D]+$/gim, ""); | |
}; |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { Component } from "react"; | |
import TextField from "../components/ui/TextField"; | |
import { View } from "react-native"; | |
const phoneRegex = "+([000]) [000] [00] [00]"; | |
const dateRegex = "[00]/[00]/[0000]"; | |
const moneyRegex = "$[000],[00]"; | |
export default class InputMask extends Component { | |
state = { phone: "", date: "", money: "" }; | |
render() { | |
return ( | |
<View style={{ padding: 12 }}> | |
<TextField | |
value={this.state.phone} | |
label='Default Flat Input' | |
autoFocus={true} | |
onChangeText={res => { | |
let val = mask(res, phoneRegex); | |
this.setState({ phone: val }); | |
}} | |
keyboardType='phone-pad' | |
/> | |
<TextField | |
value={this.state.date} | |
label='Default Flat Input' | |
onChangeText={res => { | |
let val = mask(res, dateRegex); | |
this.setState({ date: val }); | |
}} | |
keyboardType='phone-pad' | |
/> | |
<TextField | |
value={this.state.money} | |
label='Default Flat Input' | |
onChangeText={res => { | |
let val = mask(res, moneyRegex); | |
this.setState({ money: val }); | |
}} | |
keyboardType='phone-pad' | |
/> | |
</View> | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment