comment alerter un utilisateur si l'utilisateur tape un symbole dans une saisie de texte dans react? J'ai essayé ceci
textChange = () => {
if (this.state.texts == new RegExp(/[^a-zA-Z\s]/) ) {
alert("No symbols allowed")
}
}
mais le fait de noter est une alerte lorsqu'un symbole est de type
3 Réponses :
Au lieu de comparer l'égalité de la chaîne avec l'objet regex, vous devez utiliser test méthode, qui renvoie une valeur booléenne basée sur le modèle de correspondance de chaîne passé ou non
textChange = () => {
if (/[^a-zA-Z\s]/.test(this.state.text) ) {
alert("No symbols allowed")
}
}
Utilisez les méthodes test ou match ,
textChange = () => {
if (this.state.text.match(/[^a-zA-Z\s]/) !== null) {
alert("No symbols allowed")
}
}
ou
textChange = () => {
if (/[^a-zA-Z\s]/.test(this.state.text) ) {
alert("No symbols allowed")
}
}
Vous pouvez utiliser la méthode text de javascript pour valider à l'aide d'une expression régulière.
textChange = () => {
const expression = /[^a-zA-Z\s]/;
var notValid = expression.test(String(this.state.texts));
// notValid will be true if entered text does'nt match the expression
if(notValid){
alert("No symbols allowed");
}else{
//Valid value
}
}
Essayez
if (new RegExp (/ [^ a-zA-Z \ s] /). Test (this.state.texts))Ou
/[^a-zA-Z\s /.test(this.state.texts)