jquery validation allow to enter code between user1 to user100 - javascript

This is my the example where user can enter the code between 1 to 100 only otherwise return false.
var regexCode = /var regexEmail = /^0*(?:[1-9][0-9]?|100)$/;
$(document).on('change','#code',function(){
if (!regexCode.test($("input#code").val())) {
alert("Please enter valid code");
$("input#code").focus();
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input name="code" id="code" placeholder="code" required>
Now it accepting digits between 1 to 100 but I need it to accept the code e.g between
user1 to user100 only otherwise return false.

lot of solution with : regexp
var regexCode = /^user(?:[1-9][0-9]{0,1}|100)$/;
$(document).on('change','#code',function(){
var result = $("input#code").val();
if (!regexCode.test($("input#code").val())) {
alert("Please enter valid code");
$("input#code").focus();
return false;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<input name="code" id="code" placeholder="code" required>

You can use this regex /^[1-9][0-9]$|^100$/ explain:
^[1-9][0-9]? should mens starts digit with two or one (first doesn't accept 0 )range number - 0 --> 99
| or operator
^100$ start and end only with the number 100
also think to remove last added number from value using :
value = value.substring(0, value.length - 1);
$(this).val(value);
Belw in snippt I've used on Input event to check for every keyboard input
var regexCode = /^[1-9][0-9]?$|^100$/;
$(document).on('input','#code',function(e){
let value = $(this).val();
if (!regexCode.test($(this).val())) {
alert("Please enter valid code");
value = value.substring(0, value.length - 1);
$(this).val(value)
$("input#code").focus();
return false;
} else {
$("#output").html("user"+value)
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input name="code" id="code" placeholder="code" required> rang betwwen 0-100
<br><br>
user id = <span id="output"></span>

You can use HTML Pattern for this purpose.
<input type="text" name="code" id="code" placeholder="code" pattern="user[0-9]{1,2}" required />

Related

How to perform string methods on function parameter in javascript

I am trying to write some javascript code to validate an HTML form and I am stuck. I am suspecting there are multiple issues (I am really new to JS) but the one I am stuck at is preventing me from further troubleshooting. Essentially, I need to have 2 functions, validatePassword and validateForm, one to validate the password and another to validate the rest of the input. The password needs to have an uppercase letter and be at least 8 characters long.
My main problem right now is that I do not know how to convert validatePassword's parameter to a string to check its length and whether it has an uppercase letter or not.
(Please let me know if you see any other problems with my code.)
Here it is:
// add validatePassword function here
function validatePassword(str) {
let value = String(str);
if (value.length < 8 && value !== value.toLowerCase()) {
return true;
}
return false;
}
const validateForm = (myForm) => {
// get text of fields
var firstname = myForm.firstname.value;
var lastname = myForm.lastname.value;
var password = myForm.password.value;
firstname != null
? true
: $("#message").html("Please enter a first name");
lastname != null
? true
: $("#message").html("Please enter a last name");
/* Form validation*/
validatePassword(password) == true
? true
: $("#message").html("Password incorrect");
return false; // prevent page reload
};
<head>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
</head>
<body>
<form id="form1" action="#" onsubmit="return validateForm(this);">
first name: <input type="text" name="firstname" /><br />
last name: <input type="text" name="lastname" /><br />
password: <input type="text" name="password" /><br />
<button>Check</button>
</form>
<hr />
<div id="message"></div>
</body>
A few problems here:
There was a logic error in validatePassword (and some typos). You want the password to be invalid if the length is < 8 or the value is equal to its lowercase. Personally I would return true is the password was valid, but to each their own.
It is more conventional to use if statements instead of the ternary operator if you don't need its return value.
You need to reset the error message string if nothing is wrong in the form (this can be done before checking any of the fields).
// add validatePassword function here
function validatePassword(str) {
let value = String(str);
if (value.length < 8 || value === value.toLowerCase()) {
return true; // invalid password
}
return false; // valid password
}
const validateForm = (myForm) => {
// get text of fields
var firstname = myForm.firstname.value;
var lastname = myForm.lastname.value;
var password = myForm.password.value;
$("#message").html("");
if (!firstname) {
$("#message").html("Please enter a first name");
}
if (!lastname) {
$("#message").html("Please enter a last name");
}
/* Form validation*/
if (validatePassword(password) === true) {
$("#message").html("Password incorrect");
}
return false; // prevent page reload
};
<head>
<script src="https://code.jquery.com/jquery-3.6.3.min.js"></script>
</head>
<body>
<form id="form1" action="#" onsubmit="return validateForm(this);">
first name: <input type="text" name="firstname" /><br />
last name: <input type="text" name="lastname" /><br />
password: <input type="text" name="password" /><br />
<button>Check</button>
</form>
<hr />
<div id="message"></div>
</body>
Few observations/suggestions :
As password is always consider as a sensitive field, It should be a type of password instead of text. (No need to worry about the data type while getting it, You will get it as a string only)
As per the mentioned validation criteria for password The password needs to have an uppercase letter and be at least 8 characters long. Condition should be :
value.length <= 8 && value !== value.tolowerCase()
myForm.password.value will return a string only. Hence, No need to convert String into a String again.
Your final password validation function would be :
function validatePassword(value) {
return (value.length <= 8 && value !== value.tolowerCase()) ? true : false;
}

using HTML variables with JavaScript

I'm creating a sign up system and tying to make a code using JavaScript that checks the phone number the user is entering and only allows it to be used if it is 10 characters long.
this is my code so far:
JavaScript:
<script type="text/javascript">
function phoneIsValid()
{
var phoneL = document.getElementById("phone").length;
if (phoneL != 10)
{
document.getElementById("phoneErr").innerHTML = "invalid phone number"
return false;
}
else
{
document.getElementById("phoneErr").innerHTML = "";
return true;
}
}
</script>
HTML:
<input type="text" id="phone" name="phone" />
<a id="phoneErr"></a>
the problem is that it always replys that the phone number is not 10 cahracters long, even if it is. what am I doing wrong? I dont know much Javascript and I cant find a solution on the internet.
You don't even need JS for this:
<form>
<input type="text" minlength="10" maxlength="10" required placeholder="Phone number (10 digits)" />
<button>Send</button>
</form>
function phoneIsValid()
{
var phoneL = document.getElementById("phone").value.length;
if (phoneL != 10)
{
document.getElementById("phoneErr").innerHTML = "invalid phone number"
return false;
}
else
{
document.getElementById("phoneErr").innerHTML = "";
return true;
}
}
function checkPhone() {
if(phoneIsValid()) {
alert('Phone number is valid');
} else {
alert('Phone number is NOT valid');
}
}
<input type="text" id="phone" name="phone" />
<a id="phoneErr"></a>
<button type="button" onclick="checkPhone()">Check it</button>
As mentioned in comments - you need to validate value of the textbox, not textbox itself.
It'd be quite simple
HTML: First create a submit button, so that we can detect when the user submits it
<input type="text" id="phone" name="phone" placeholder='Enter Phone number..'/>
<button id='submit'>Submit</button>
JavaScript:
<script type="text/javascript">
document.getElementById('submit').onclick = function(){ // trigger when button is clicked
let phoneL = document.getElementById('phone').value.length; // get the length of the value
if (phoneL >= 10) { //check if the length is 10 characters or more
alert('Valid phone number!')
} else {
alert('Invalid phone number!')
}
}
</script>
If you need any other help, feel free to let me know
Try getting the length of the "value".
var phoneL = document.getElementById("phone").value.length;
˄

Regular Expression for input type number want 10 digit only? Only accept whole number

I have made a form in which I want that in the mobile number field it must take only 10 digit. If it exceed than replace with space "".And want that my user not able to enter more than 10 digits. I only want to do with Regular Expression. I don't want to do it with maxlength because maxlength not work with type number in input element.
function nValid(){
var elem=document.getELementById("mNumber");
var mNumber=elem.value;
var status=document.getElementById("status");
var regex=/\d{10}/;
if(mNumber==""){
status.innerHTML="Please enter the mobile number.";
}else if(mNumber.match(regex)==null || mNumber.length>10){
status.innerHTML="Please enter upto 10-digit mobile number";
//here I want Regular Expression elem.value=mNumber.replace(regex,"");
}else{
status.innerHTML="Looks good!";
}
}
<form>
<label for="mNumber">Mobile Number</label>
<input type="number" id="mNumber" oninput="nValid()"/>
<small id="status" class="text-form text-muted"></small>
</form>
I'd do it like this.
function nValid(elem){
var mNumber = elem.value;
var status = document.getElementById("status");
if(mNumber.length == 0) {
status.innerHTML = "Please enter the mobile number";
} else if (!/^\d+$/.test(mNumber) || mNumber.length > 10) {
status.innerText = "The number can only consist of up to 10 digits";
setTimeout(function() {
elem.value = mNumber.replace(/[^\d]+/, '').substring(0, 10);
status.innerText = "Looks good!";
}, 500);
} else {
status.innerText = "Looks good!";
}
}
<form>
<label for="mNumber">Mobile Number</label>
<input type="text" id="mNumber" oninput="nValid(this)"/>
<small id="status" class="text-form text-muted"></small>
</form>
function nValid(){
var elem=document.getElementById("mNumber");
var mNumber=elem.value;
var status=document.getElementById("status");
var regex=/\d{10}/;
if(mNumber==""){
status.innerHTML="Please enter the mobile number.";
}else if(mNumber.match(regex)==null || mNumber.length>10){
status.innerHTML="Please enter upto 10-digit mobile number";
if(mNumber.length>10){
elem.value=mNumber.replace(/.$/g,"");
status.innerHTML="Looks good!";
}
}else{
status.innerHTML="Looks good!";
}
}
<form>
<label for="mNumber">Mobile Number</label>
<input type="number" id="mNumber" oninput="nValid()"/>
<small id="status" class="form-text text-muted"></small>
</form>

Minimum and Maximum length of User Input

I have a form in which a user enters a 13 digits numeric value and i try to use minlength attribute but its not working. So i try javascript and it works fine but when the focus losses from Input then the function onblur calling again and again. the code is under
HTML
<input type='number' id='cnc' pattern='[0-9]{13,13}' name='cnic' oninput="javascript: if (this.value.length > 13) this.value = this.value.slice(0, 13);" minlength="13" onblur="checkLength(this);" placeholder="Enter CNIC without dashes: e.g 6110122334455" class='form-control' required value="<?php echo isset($_POST['cnic']) ? htmlspecialchars($_POST['cnic'], ENT_QUOTES) : ""; ?>" />
Javascript
function checkLength(el) {
if (el.value.length != 13) {
alert("CNIC length should be 13 digits");
document.getElementById("cnc").focus();
document.getElementById("cnc").select();
}
Now i want that the control/cursor to the input field if user not entered 13 digit code and moves to other input field
Try this regex method to verify the Pakistani CNIC format:
jQuery('#cnic').blur(function(){
var input_text = jQuery(this).val(),
myRegExp = new RegExp(/\d{5}-\d{7}-\d/);
if(myRegExp.test(input_text)) {
//if true
jQuery('#cninc_msg').text('Correct');
}
else {
//if false
jQuery('#cninc_msg').text('Enter CNIC in correct format. 12345-1234567-1');
}
});
jQuery('#cnic2').blur(function(){
var input_text = jQuery(this).val();
if(input_text.length != 13 ){
jQuery('#cninc2_msg').text('Error');
}
else{
jQuery('#cninc2_msg').text('OK');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" id="cnic" name="cnic" placeholder="42212-1234567-1" />
<span id="cninc_msg"> </span>
Without Dashes simply check this
<input type="text" id="cnic2" name="cnic" placeholder="4221212345671" />
<span id="cninc2_msg"> </span>
This is just a basic example. You can use this on on key up or onkeyDown events as per your requirements.
minlength is not yet supported by any browser. Try this instead

How can I change HTML5 form validation default error messages for min and max?

I found this answer for changing error message for invalid values How can I change or remove HTML5 form validation default error messages?.
I need to show different message for value less than min and more than max.
<input type="number" name="test" step="any" min="0.01" max="10.0">
If user enters -1, it should say "Please enter positive value".
If user enters 20, it should say "Value cannot be more than 10".
There may be some fancy API-driven way to do it, but if the title is displayed when the input doesn't match a pattern, you can just modify the the title on change.
To support decimals, you'll need some fancier regex.
*I included the form tag so the validation would work in the snippet
document.querySelector('input').addEventListener('change', (e) => {
if (e.target.value > 10) {
e.target.setAttribute('title', "Value cannot be more than 10");
} else if (e.target.value < 0) {
e.target.setAttribute('title', "Please enter a positive value");
} else {
e.target.setAttribute('title', "Please enter a number");
}
})
<form><input type="text" required="" pattern="10|[0-9]" value="" title="This is an error message" /></form>
With the HTML5 form validation (from your link) you can use a custom message by using the invalid event listener on the input element.
var myInput = document.getElementById("myInput");
myInput.addEventListener("invalid", validate);
myInput.addEventListener("keyup", validate);
function validate() {
var val = parseFloat(this.value);
var min = parseFloat(this.min);
var max = parseFloat(this.max);
if (val < min) {
this.setCustomValidity('Please enter a positive number');
} else if (val > max) {
this.setCustomValidity('Value cannot be more than ' + max);
} else {
this.setCustomValidity("");
}
}
<form>
<input id="myInput" type="number" name="test" step="any" min="0.01" max="10.0">
<button type="submit">Submit</button>
</form>

Categories

Resources