RegEx for fixed number of digits? - javascript

I'm finishing a form I have to do for my homework, and just when I thought I was finished, I found a mistake.
I need a RegEx for input field that would return an alert if there's not exactly 13 digits.
While I know the correct RegExp for this is: /^\d{13}$/, I also need it to ignore an empty field. (Because I don't want the alert to trigger in case the user switches to a different input field)
Just when I thought I had it with: /^$|\d{13}$/, it turns out that it will return an alert if there are less than 13 digits but not if there are more, unlike /^\d{13}$/ that is working fine with 14+ digits.
Can someone help me out with this? Thanks
Here's the rest of the function:
function checkNum(box) {
var re= new RegExp(/^$|\d{13}$/);
if(!box.value.match(re)) {
alert("13 numbers are required");
document.getElementById("numbers").value = '';
}
}
And here is the input field:
<input type="text" name="numbers" id="numbers" placeholder="Numbers" onFocus="this.placeholder=''" onBlur="checkNum(this); this.placeholder='Numbers'"/>

Very close!
/^$|^\d{13}$/
You just forgot to specify that the 13 digits started at the start of the string

Also, just an alternative to match(), for quicker boolean check use test()
if (!/^\d{13}$/.test(box.value)) {
alert("13 numbers are required");
document.getElementById("numbers").value = '';
}

Related

JS validation numbers only?

I have 5 text boxes I will get prices how can I validate there is only numbers on those text boxes if there is a letter I want to give a alert when submit.
How can I do that please help me Im new to these stuff
<input type="text" id="sellingPrice"><br>
<input type="text" id="basicPrice"><br>
<input type="text" id="latestBuyingPrice"><br>
<input type="text" id="ReorderQuantity"><br>
<input type="text" id="reorderLevel"><br>
<button id="save_P" type="button" class="save-button-text save-button displayShow" onclick="submitDetails()">
how can I use number validation in submitDetails() method
This is a pretty common issue, but there are a couple ways to approach it:
Verify using Regular Expressions
Attempt to parse the number and check if isNaN(parsedResult) returns true
By far, I believe the most common approach is var num = parseFloat(StringNumberFromTextbox), isValidNumber = (!isNaN(num) && isFinite(num));
If you went the RegEx route, you could use: var rNumPattern=/^\d+(\.\d+)?$/, isValidNumber = rNumPattern.test(StringNumberFromTextbox);
You might also consider consider checking negative/positive signs and thousands separators using replacements of commas or periods (as appropriate for the locale/clientele).
Of course, if you are then submitting those on a form to some backend processor, you would be wise to check those numbers again on the server-side rather than blindly trusting that the client has provided valid numbers just because your JavaScript should done the checking. Lest you end up with a SQL vulnerability or the like.
You can add type="number" attribute to input tag.
In submitDetails() use following code.
var sellingPrice=document.getElementById("sellingPrice").value;
//repeat above code for all field.
if(Number.isInteger(sellingPrice) == false){
alert('wrong value entered');
}
//repeat above if code for all value.
This will do what you want.
You can check it using isNaN(value) inbuilt function of JavaScript.
Your function could be like this:
function submitDetails() {
var val = document.getElementById("sellingPrice").value;
if (isNaN(val)) {
// show alert here
}
}

Javascript regExp Input Validation

This is my first post and i think the answer is very easy but i don't get it:
I (try) to build a shopify store but i have to make some modifications and here is the point at where i am stuck:
On my Product Page i want to inluce a <input type=text>, which is required, can only be Capital Letters and the length must min. be 1 and max. 10. I tried it with html5 pattern but it didn't worked. I read something, that if the shopify theme includes ajax, it just ignores the pattern and the required attribute (i don't know if this is true).
So i tried to make my own functions:
$('#dein-text').on("change textInput input", function(evt) {
$(this).val(function (_, val) {
return val.toUpperCase();
});
});
this just should return the string into capital letters.
function checkText() {
var re = /(?=.*[A-Z]).{1,6}/;
if(re.test($('#dein-text').val())) {
$('#problem-bei-input').hide();
$('.add', $product).removeClass('disabled').removeAttr('disabled');
} else {
$('#problem-bei-input').show();
$('.add', $product).addClass('disabled').attr('disabled', 'disabled');
}
}
this function is executed at every change on the input form:
$('#dein-text').on("change textInput input", checkText);
This does not work, because it removes the disabled class if there is min. 1 letter (it does not check if there are more than 6) and if there is one capital letter (something like "HA11" does not add the (.disabled) class).
i hope i could describe what my problem is.
Thank you for your help!
edit: this is the .liquid code of the whole form:
https://codepen.io/shawdyy/pen/PmOPWy
(i hope you can see this on codepen, sry i am really new to the webdev thing)
You can try:
$('#my_id').on("change input", function(evt) {
$(this).val(function (_, val) {
return val.toUpperCase().replace(/[^A-Z]/, "").replace(/^([A-Z]{1,10}).*$/g, "$1");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="my_id">
To only allow one to ten uppercase ASCII letters in the input field use the following HTML5 pattern:
<input type="text" pattern="[A-Z]{1,10}" title="Only 1 to 10 uppercase ASCII letters allowed!">
If you need to match a string that only contains 1 to 10 uppercase ASCII letters in plain JS, you need
 var re = /^[A-Z]{1,10}$/;
Note that start and end anchors (^ / $) are added by the HTML5 automatIically when using the regex in the pattern attribute.

Regex to validate a password [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Password validation regex
between 8 and 16 characters, with at least 1 character from each of the 3 character classes -alphabetic upper and lower case, numeric, symbols.
I have this code, but it doesn't work, when I write more than 16 characters, gives it as valid, but it should not; the it should to work ok with 3 character classes, but it works with 4, where's my mistake??
http://jsbin.com/ugesow/1/edit
<label for="pass">Enter Pass: </label>
<input type="text" id="pass" onkeyup="validate()">
Script
function validate() {
valor = document.getElementById('pass').value;
if (!(/(?=.{8,16})(?=.*?[^\w\s])(?=.*?[0-9])(?=.*?[A-Z]).*?[a-z].*/.test(valor))) {
document.getElementById('pass').style.backgroundColor = "red";
} else {
document.getElementById('pass').style.backgroundColor = "#adff2f";
}
}
Regular expressions are not a panacea. It's not too hard to do it, mixing with regular code:
function validatePassword(password) {
// First, check the length.
// Please see my comment on the question about maximum password lengths.
if(password.length < 8 || password.length > 16) return false;
// Next, check for alphabetic characters.
if(!/[A-Z]/i.match(password)) return false;
// Next, check for numbers.
if(!/\d/.match(password)) return false;
// Next, check for anything besides those.
if(!/[^A-Z\d]/i.match(password)) return false;
// If we're here, it's valid.
return true;
}
However, I'd look into something like zxcvbn, a password checker, which I think is a better password quality checker, checking things like common dictionary words after un-13375p3/-\kification and dealing with entropy decently. It is used, among others, by Dropbox. Try it here.
You need to anchor the match to the beginning of the string, and anchor the first lookahead to the end:
^(?=.{8,16}$)
Also, the last lookahead needs to be split in two:
(?=.*?[A-Z])(?=.*?[a-z])
Why don't you just test for the three character sets with regular expressions:
[A-Za-z0-9]+
Then count the length of the string to validate the length.
What about this range:
/[A-Za-z0-9$-/:-?{-~!"^_`\[\]]/
So you can check first
/[A-Za-z]+/
then
/\d+/
and finally
/[$-/:-?{-~!"^_`\[\]]+/
If it passes you can check the length.
You can see this link to see why the symbols work.

Javascript regexp using val().match() method

I'm trying to validate a field named phone_number with this rules:
the first digit should be 3 then another 9 digits so in total 10 number example: 3216549874
or can be 7 numbers 1234567
here i have my code:
if (!($("#" + val["htmlId"]).val().match(/^3\d{9}|\d{7}/)))
missing = true;
Why doesnt work :( when i put that into an online regexp checker shows good.
You should be using test instead of match and here's the proper code:
.test(/^(3\d{9}|\d{7})$/)
Match will find all the occurrences, while test will only check to see if at least one is available (thus validating your number).
Don't get confused by pipe. Must end each expression
if (!($("#" + val["htmlId"]).val().match(/^3\d{9}/|/\d{7}/)))
missing = true;
http://jsfiddle.net/alfabravoteam/e6jKs/
I had similar problem and my solution was to write it like:
if (/^(3\d{9}|\d{7})$/.test($("#" + val["htmlId"]).val()) == false) {
missing = true;
}
Try this, it's a little more strict.
.match(/^(3\d{9}|\d{7})$/)

Form validation of numeric characters in JavaScript

I would like to perform form validation using JavaScript to check for input field only to contain numeric characters.So far, the validation checks for the field not being empty - which works fine.However, numeric characters validation is not working.I would be grateful for any help.Many thanks.
<script type="text/javascript">
//form validation
function validateForm()
{
var x=document.forms["cdp_form"]["univer_number"].value
if (x==null || x=="")
{
alert("University number (URN) field must be filled in");
cdp_form.univer_number.focus();
return false;
}
else if (is_valid = /^[0-9]+$/.test(x))
{
alert("University number (URN) field must have numeric characters");
cdp_form.univer_number.focus();
return false;
}
}
</script>
<input type ="text" id="univer_number" maxlength="7" size="25" name="univer_number" />
Rather than using Regex, if it must only be numerals you can simply use IsNumeric in Javascript.
IsNumeric('1') => true;
IsNumeric('145266') => true;
IsNumeric('abc5423856') => false;
You need invert your regular expression (add ^ inside [0-9]):
/^[^0-9]+$/
Your test condition is a bit strange:
else if (is_valid = /^[0-9]+$/.test(x))
Why have the redundant comparison to is_valid? Just do:
else if (/^[0-9]+$/.test(x))
Though the regex you are using will match numerals and only numerals - you need to change it to match anything that is not a numeral - like this /^[^0-9]+$/.
Better yet, get rid of the regex altogether and use IsNumeric:
else if (!IsNumeric(x))
On your line that says else if (is_valid = /^[0-9]+$/.test(x)), you're doing a simple assignment instead of testing that it is actually matching the regex.
Your pattern will still accept this input <b>##$##123 or ad!##12<b>. Use this pattern I created:
/[a-zA-Z-!##$%^&*()_+\=\[\]{};':"\\|,.<>\/?]/
This pattern will check if it is alphabetic and special characters.
You need to test for the negation of the RegExp because you want the validation to alert upon failure, so just add ! in front of it:
else if (is_valid = !/^[0-9]+$/.test(x))
See example →
I know this is an old post but I thought I'd post what worked for me. I don't require the field to be filled at all but if it is it has to be numerical:
function validateForm()
{
var x=document.forms["myformName"]["myformField"].value;
if (/[^0-9]+$/.test(x))
{
alert("Please enter a numerical amount without a decimal point");
myformName.myformField.focus();
return false;
}
}

Categories

Resources