简体   繁体   中英

React alphanumeric validation issue

 export default (value = "") => { let error = null; const stripped = value.replace(/^[0-9a-zA-Z]*$/, ""); if (stripped.length !== value.length) { error = "Input Contains Bad Characters"; } return { error, value }; }; // This below code for varying the formats import validator from "../../validators/alpha-numeric.js"; describe("Alphanumeric Only Validator For Input Validation", () => { test("Only Characters Passed", () => { expect(validator("Abcd")).toMatchObject({ error: null, value: "Abcd" }); }); test("Alphanumeric Characters With Space", () => { expect(validator("Abc d")).toMatchObject({ error: "Input Contains Bad Characters", value: "Abc d" }); }); test("Alphanumeric Characters With Numbers", () => { expect(validator("Ab123d")).toMatchObject({ error: null, value: "Ab123D" }); }); test("Alphanumeric Characters With Special Characters", () => { expect(validator("Abcd@")).toMatchObject({ error: "Input Contains Bad Characters", value: "Abcd@" }); }); });

This is full code i am using in React, please guide me the perfect result how can i verify alphanumeric.

This is the requirement even the below describe code i have written that is for unit testing, but if i am running "yarn unit-test" so i am getting error.

This:

const stripped = value.replace(/^[0-9a-zA-Z]*$/, "");

Only replaces those characters if they're the only ones in the string, because of the anchors ( ^ and $ ).

If you want to check value only contains those characters, there's no need to create another string:

if (/[^0-9a-zA-Z]/.test(value)) {
    // It has an invalid character
}

That works because the regular expression will match any character not in 0-9, az, or AZ. If it doesn't match, there aren't any invalid characters.

Example:

 function test(value) { if (/[^0-9a-zA-Z]/.test(value)) { console.log(JSON.stringify(value), "=> invalid"); } else { console.log(JSON.stringify(value), "=> valid"); } } test(""); // Valid test("0a"); // Valid test("Ab123d") // Valid test("0a-"); // Invalid

Hello everyone i have got the solution of this question, please find the alphanumeric pattern /\\w/ . This pattern is working for me, also please find the steps for regex creation... enter link description here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM