I'm having a problem with my regex validation code. I'm trying to figure out how can I validate a vehicle license plate number. The code that I wrote is listed below this message. This is written down in React inline code and I've written down two different regex expressions and both of the come out to be false. The license plate number should be in this format XX-NNNN-XX.
X = Letter
N = Number
const [licencePlate, setLicencePlate] = useState('');
var ValidateLicencePlate = /^[A-Z][A-Z]-[0-9][0-9][0-9][0-9]-[A-Z][A-Z]$/g ;
var regex = /^[A-Z]{2}-[0-9]{4}-[A-Z]{2}$/g ;
<input name="licence-plate" type="text" className="feedback-input" maxLength='10' onChange={(e) => setLicencePlate(e.target.value.toUpperCase())} placeholder="XX-NNNN-XX"/>
This regex can solve the problem.
let regex = /^[A-Z]{2}-\d{4}-[A-Z]{2}/gi
This regex will match two alphabet at the beginning, four digits at the middle and two alphabet at the end.
You can use regex as following
<input pattern="/^[A-Z]{2}-\d{4}-[A-Z]{2}/g"/>
You can put your regex in the pattern attribute of the input element. I do not see you are using regexps yo have defined anywhere in your listing.
<input pattern={regex}/>
If you have a regex constraint to validate against it may be better and more comfortable to use Constraint Validation API.
<input pattern="your regex here"/>
Browser already validates everything in form elements if you constraint them with various ways like patter attribute and unless you tell it not to validate. But still I see many code bases trying to do the validation themselves. It is unnecessary since there is a way platform itself supports and does itself.
Related
I have the following regex pattern on an HTML input field, which is supposed to hold an email address:
<input type="text" pattern="^\w+([.-]?\w+)*#\w+([.-]?\w+)*(\.\w{2,4})+$" /><br>
I furthermore have the same regex on an Express (JavaScript) backend using the following:
var re-email = new RegExp("^\w+([.-]?\w+)*#\w+([.-]?\w+)*(\.\w{2,4})+$")
if (!re-email.test(email)) {
validation = false
}
Although the regex are exactly the same, a specific test input is evaluated as true on the front-end while as false on the backend.
Why is this?
Solution (found after the initial post):
Instead of using "new RegExp" (which is not working) as above, include the Regex within forward slashes as below (which works).
var re-email = /^\w+([.-]?\w+)#\w+([.-]?\w+)(.\w{2,4})+$/
Probably not the answer you are after (not vue.js specific)...
Email address input validation should usually be completed like so:
<input type="email" name="" value="" required />
Specifying the correct "type" to an input field also adjusts input keyboards on mobile devices to make inputting an email address easier.
Your regular expression is poorly written and leads to "catastrophic backtracking" as well as not actually supporting valid email addresses.
Email address validation is generally complex, see this answer and associated question:
https://stackoverflow.com/a/201378/406712
You can also find the HTML email address validation equivalent regular expression in the HTML spec:
https://html.spec.whatwg.org/multipage/input.html#valid-e-mail-address
Also note you failed to escape the characters in the string, the first instance being the \w which without escaping the \ will appear as simply w.
Escaped the string it more like this:
'/^\\w+([.-]?\\w+)#\\w+([.-]?\\w+)(.\\w{2,4})+$/'
I'm looking for a solution that will solve the following problem but only have limited experience with Unicode.
Basically the user is able to type into a text field, however when they submit i want to display a list of the characters that WEREN"T GSM compliant. I.E everything that doesn't have a char code of 0-127.
However, it breaks severely when you bring emojis into the mix because if i char array it some emoji characters will get broken up and it will display the wrong reason why the validation failed.
I.E "π".length = 2, it will get split into 2 characters and therefore when i tell the user why it failed they will get the wrong reason.
Any ideas on how i can solve this would be greatly appreciated.
EDIT: Can't use ES6 and need an array of the invalid characters
Supposing youβre using a regex like this to find characters that arenβt in the valid range:
/[^\0-\x7f]/
you can modify it to prefer to match UTF-16 surrogate pairs:
/[\ud800-\udbff][\udc00-\udfff]|[^\0-\x7f]/
On modern browsers, you can also just use the u flag to operate on Unicode codepoints directly:
/[^\0-\x7f]/u
This will still only get codepoints, though, and not grapheme clusters (important for combining characters, modern combined emoji, skin tone, and general correctness in all languages). Those are harder to deal with. When (if?) browser support appears, they will be less hard; until then, a dedicated package is your best bet.
var NON_GSM_CODEPOINT = /[\ud800-\udbff][\udc00-\udfff]|[^\0-\x7f]/;
var input = document.getElementById('input');
input.addEventListener('input', function () {
var match = this.value.match(NON_GSM_CODEPOINT);
this.setCustomValidity(match ? 'Invalid character: β' + match[0] + 'β' : '');
this.form.reportValidity();
});
<form>
<textarea id="input"></textarea>
</form>
You can use the spread operator (...) to break the characters into an array and then charCodeAt to get the value:
let str = `πabcπdefπghi`;
let chars = [...str];
console.log(`All Chars: ${chars}`);
console.log('Bad Chars:',
chars.filter(v=>v.charCodeAt(0)>127)
);
Interesting! This is merely trial and error, but looks like converting the string to an array of chars strings using Array.from will allow you to index the characters correctly:
Array.from('π').length
1
Array.from('πabc').length
4
Array.from('πabc')[0]
"π"
I am new to javascript and I couldn't find the exact code for my need.
I want a text field with maxlength="5" which should look like ex:AE456, LM975. i.e., the first two letters ahould be alphabets and next three letters should be numbers.
the text area should accept input according to this pattern only. I don't want any alert. Simply it has to accept whatever typed only in this pattern.
Javascript is preferrable. Any help is greatly appreciable.
Thanks in advance.
HTML5 supports pattern where a field can accept values as per the supplied regex. You can find related post here.
Regex Patterns for HTML5 Text Field
But if you want to support older browser, then you have to attach events like "keypress" to the input field, and handle the event to validate the input
If you have this HTML:
<input type="text" id="text1" />
Then you could use this Javascript:
function validateInput() {
var val = document.getElementById("text1").value;
return /[A-Z]{2}\d{3}/i.test(val);
}
and call it like:
if (validateInput()) {
// Matches pattern: #####
}
DEMO: http://jsfiddle.net/GgQsz/
This allows uppercase and lowercase alpha characters at the beginning. If you want to only allow uppercase, remove the i flag for the Regex.
What you need is a regular expression. Check out regular expression here. This should give you an idea as to how to check for your condition.
http://www.w3schools.com/jsref/jsref_obj_regexp.asp
I'm currently working on a project in which I need to fetch street/city details from a DB using a zipcode. Dutch zipcodes use a "1111 AA" format, I would like to have this entered in a single input field while forcing the first four characters to be numeric and the last two to be alphabetical.
I've been googling this quite a bit, have found ways to force either one, but none to combine it into a single input field and I don't seem to be crafty enough to combine them myself.
Thank you.
We use this in alot of sites, especially for phone #s
http://digitalbush.com/projects/masked-input-plugin/
To handle the specific pattern you entered, try something like this in the javascript function that validates form input:
var pattern = new RexExp( '[0-9]{4} [A-Z]{2}' );
if( inputFieldValue.search( pattern ) == -1 )
{
// throw error condition.
}
else
{
// The pattern matched. Continue on.
}
This is finally a question where regular expressions are a suitable solution.
Try this:
var zip = "1111 AA"
var regex = new RegExp("^[0-9]{4}\\s?[A-Z]{2}$");
regex.test(zip);
Note that this will not allow lowercase characters, and will allow the zipcode without whitespace (like this: 1111AA). Try some googling to find out how to allow or disallow those.
You can use the new html5 pattern attribute for that:
<form>
<input name="zipcode" type="text" pattern="\d{4}\s?[A-Z]{2}" length="7" />
<input type="submit" />
</form>ββββββββββββββββββββββββ
If the attribute isn't supported, you fall back to a javascript solution, checking the input field with a regex before submit like the following:
var pattern = /[0-9]{4}\s?[A-Z]{2}/;
string.match(pattern);
Take a look at the demo fiddle.
I know that SO is not a code generator, but I break my head and I'll got mad with this RegExp.
I've <input /> type text, in a HTML <form />. The input is automatically filled when the user double-click on elements in a specific list.
This event will generate string like "[text:number]" or "[text:number:text]", and place it at the cursor position in my <input /> field.
The first goal of this process is to construct a mathematic formula structure. I mean, the generated strings between brackets will insert elements, then I want to allow the user to put only numbers and operators.
I've tried to bind the keydown event, and test the char with String.fromCharCode(e.which); but for the keys "+" or "-" (and other operators) this function returns alphabeticals chars. Without success.
Then, I've finally decided to use the keyup event, then use a RegExp to replace the <input /> value.
$("#inputID").keyup(function(){
var formule = $(this).val();
var valid_formule = formule.replace(CRAZY_REGEXP,'');
$(this).val(valid_formule);
});
So, my question is as follows :
How construct a javascript RegExp, to remove all chars which are not between brackets, and which are differents of ()+-*/,. and numbers.
An example :
"a[dse:1]a+a[dse:5]a+a[cat:5:sum]a+(a10a/5,5)!"
will become
"[dse:1]+[dse:5]-[cat:5:sum]+(10/5,5)"
I'm open to another way to achieve my goal if you have some ideas.
Thanks !
You may try something like this:
var re = /[^\]\d\(\)+\-*\/,.]+(?=[^\[\]\(\)]*(?:\[|\(|$))/g;
$("#inputID").keyup(function(){
this.value = this.value.replace(re, "");
});
Keep in mind, though, that you have to be sure that the parenthetical structure is coherent with your syntax.
Advice: use RegExr to test your regular expressions, but remember that it's more powerful than Javascript regex support.