I need to validate some data in java script where I can enter values >= 0.25 to 99.0 and Only 2 digit after decimal.
Here is an example of how you can do it:
frm.onsubmit = function () {
var value = frm.num.value;
if (+value >= 0.25 && +value <= 99 && /^\d+(\.\d{0,2})?$/.test(value)) {
msg.textContent = 'ok';
return false; // remove this to allow submission to happen
} else {
msg.textContent = 'not valid';
return false;
}
};
<form id="frm">
<input name="num"> <span id="msg"></span><br>
<button>Validate and Submit</button>
</form>
Related
this maybe a simple question but not for me. I have a form that has a phone number field in i have JS to restrict users to a certain format. The problem is when they input less then 10 digits it still allows them to submit.
Here is my js:
$('#phone-number')
.keydown(function (e) {
var key = e.which || e.charCode || e.keyCode || 0;
$phone = $(this);
// Don't let them remove the starting '('
if ($phone.val().length === 1 && (key === 8 || key === 46)) {
$phone.val('(');
return false;
}
// Reset if they highlight and type over first char.
else if ($phone.val().charAt(0) !== '(') {
$phone.val('(' + String.fromCharCode(e.keyCode) + '');
}
// Auto-format- do not expose the mask as the user begins to type
if (key !== 8 && key !== 9) {
if ($phone.val().length === 4) {
$phone.val($phone.val() + ')');
}
if ($phone.val().length === 5) {
$phone.val($phone.val() + ' ');
}
if ($phone.val().length === 9) {
$phone.val($phone.val() + '-');
}
}
// Allow numeric (and tab, backspace, delete) keys only
return (key == 8 ||
key == 9 ||
key == 46 ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
})
.bind('focus click', function () {
$phone = $(this);
if ($phone.val().length === 0) {
$phone.val('(');
}
else {
var val = $phone.val();
$phone.val('').val(val); // Ensure cursor remains at the end
}
})
.blur(function () {
$phone = $(this);
if ($phone.val() === '(') {
$phone.val('');
}
});
This is the phone number box:
<div class="form-group">
#Html.LabelFor(m => m.phoneNumber)
#Html.TextBoxFor(m => m.phoneNumber, new { #class = "form-control", minlength = "5", oncopy = "return false", onpaste = "return false",
id = "phone-number" ,name = "phone-number", type = "text", maxlength = "14" , placeholder = "(XXX) XXX-XXXX"
})
</div>
This is the Submit btn
<button type="submit" class="btn btn-primary" value="Results" id="Submit" disabled="disabled" >Submit</button>
I don't know if you need this information but this Enable the submit btn after the boxes are filled in JS
$("input[type=text]").keyup(function () {
if
(
$("#firstName").val().trim().length !== 0 &&
$("#lastName").val().trim().length !== 0 &&
// $("#phoneNumber").val().trim().length !== 0 &&
$("#address").val().trim().length !== 0
) {
$("#Submit").removeAttr("disabled");
$("#Submit").addClass("btn--primary");
} else {
$("#Submit").attr("disabled", "disabled");
}
});
Thank you and sorry if it is an easy question but I tried in many places.
What you want to do is stop the form submission from going through. You can do this by attaching an on submit event to the form and preventDefault within it. For example:
$('#FORM_ID').submit(function (e) {
if ($('#phone-number').val().replace(/[^\d]/g,'').length < 10){ // check if phone number is less than 10 digits
// phone number is less than 10 digits, prevent form submission
e.preventDefault()
return false
}
})
Let me know if you have any questions!
Here's how my validation of the phone number input ($('#phone-number').val().replace(/[^\d]/g,'').length < 10) works:
I get the value of the phone number input: $('#phone-number').val()
I remove any characters that are not numbers replace(/[^\d]/g,'')
Then I get the length of the resulting numbers. If it's less than 10, I prevent the form from submitting via e.preventDefault()
Note: you will have to replace #FORM_ID with the id of the form you want to run this validation for.
Have you considered using an input with type="tel" and the pattern attribute? It doesn't disable the submit button like you asked, but it can validate the user input against a certain pattern.
Below a few examples of inputs using a pattern. The first accepts exactly 10 digits, the second accepts 10 digits or more, the third accepts a strict format similar to your inputs placeholder:
<form>
<input type="tel" pattern="[0-9]{10}" placeholder="Exactly 10 digits"><br>
<input type="tel" pattern="[0-9]{10,}" placeholder="10 digits or more"><br>
<input type="tel" pattern="\([0-9]{3}\) [0-9]{3}-[0-9]{4}" maxlength="14" placeholder="(123) 456-7890"><br>
<input type="submit">
</form>
thank you for the help but for me this works the best and easiest.
//This script will prevent the user from Submitting if the Phone number box is less than
function validatePhone() {
var phoneNumberPattern = /^\(?(\d{3})\)?[- ]?(\d{3})[- ]?(\d{4})$/;
var phoneNumber = $("#phone-number").val();
if (phoneNumberPattern.test(phoneNumber)) {
return true;
}
return false;
}
//Here we make sure that all boxes are filled then Submit.
$("input[type=text]").keyup(function () {
if
(
validatePhone()
) {
$("#Submit").removeAttr("disabled");
$("#Submit").addClass("btn--primary");
} else {
$("#Submit").attr("disabled", "disabled");
}
});
//this is the submit btn
<div class="form-group">
<button type="submit" class="btn btn-primary" value="Results" id="Submit" disabled="disabled">Submit</button>
</div>
i am trying to covert decimal places on type input field like
Number starts from 0.00
so at first place it will be 0.00 in input field
than i type 1 than it should become 0.01
than i type 2 than it should become 0.12
than 0 so it should become 1.20 and lastly
when i type 0 than it should become 12.00
0.01, 0.12, 1.20, 12.00.
I tried some methods which already given in SO but not successful.
Please suggest me another methods if possible. thank you.
i tried like this
$(document).on('keyup','.price',function(e){
var value = $(this).val();
if(value.length <= 6) {
if(e.which == 190 || e.which == 46 || e.which == 44 || e.which == 188){
var amountDots = 0;
var amountCommas = 0;
if(value.indexOf(',') > -1){
amountCommas = value.match(/,/gi).length;
}
if(value.indexOf('.') > -1){
amountDots = value.match(/./gi).length;
}
if((amountDots >= 1 && amountCommas >= 1) || amountCommas > 1 || value.length == 1){
$(this).val(value.substr(0,value.length - 1));
return false;
}
else{
$(this).val(value.substr(0, value.length - 1) + ',');
}
}
$(this).val(value/100); //here is the value will insert
} else {
$(this).val(value.substr(0,value.length - 1))
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" class="price" />
Ok, totally different solution that works when deleting characters:
$(document).on('keypress','.price',function(e){
var char = String.fromCharCode(e.which);
if(isNaN(char)) char = '';
var value = $(this).val() + char;
value = value.replace('.','');
$(this).val((value/100).toFixed(2));
if(!isNaN(char)) return false;
}).on('keyup','.price',function(e){
var value = $(this).val();
value = value.replace('.','');
$(this).val((value/100).toFixed(2));
});
https://jsfiddle.net/14shzdo5/
With each new keystroke, assuming it's a number, append it to the end, multiply by 10 and display the result.
The following logic works for the basic scenario. You may have to separately handle clearing out the text input.
$(document).ready(function() {
$("#my-input").on('keyup', function(e) {
var v = String.fromCharCode(e.keyCode);
if (!isNaN(v)) {
var dv = $("#my-display").val();
$("#my-display").val(dv + '' + v);
$(this).val(($("#my-display").val() / 100).toFixed(2));
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<input type="text" id="my-input" />
<input type="hidden" id="my-display" />
I want to change my error message depending on how many digits the user enters in credit card field. I'm trying to generate the message variable with this:
let numberDigit;
let creditCardMessage;
if ($cardNumber.val().length < 13) {
numberDigit = 'Too few digits. ';
} else if ($cardNumber.val().length > 16) {
numberDigit = 'Too many digits. ';
}
creditCardMessage = numberDigit + 'Please enter between 13 and 16';
Then I want to pass the creditCardMessage variable in the following function:
function creditCardNumberEvent () {
if (!isCreditCardValid()) {
showErrorMessage ($cardNumber, creditCardMessage, $cardNumber, 'creditCardError');
} else {
removeErrorMessage($cardNumber, '#creditCardError');
}
}
All I get is the first value - the "too few digits." Thanks in advance.
When running your script, you can call CardNumberValid() which returns a Boolean, meaning you can use it in an if statement, like if(CardNumberValid())
function CardNumberValid() {
var valid = true;
var CardNumber = $("#CardNumber");
if (CardNumber.val().length < 13) {
$("#ErrorMsg").text("Too few digits. Please enter between 13 and 16");
valid = false;
} else if (CardNumber.val().length > 16) {
$("#ErrorMsg").text("Too many digits. Please enter between 13 and 16");
valid = false;
}
if(valid){
$("#ErrorMsg").text("");
}
return valid;
}
$('#Validate').click(function() {
alert("The card number " + (CardNumberValid() ? "is" : "is not") + " valid.");
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="CardNumber" />
<div id="ErrorMsg" style="color:red;"></div>
<button id="Validate" type="button">Validate</button>
I think this is what you're trying to achieve:
function logValidationMessage() {
var cardNumber = document.getElementById('cardNumber');
var numberDigits = null;
if (cardNumber.value.length < 13) {
numberDigits = 'Too few digits. ';
} else if (cardNumber.value.length > 16) {
numberDigits = 'Too many digits. ';
} else {
numberDigits = 'Card number is valid.';
}
console.log(numberDigits);
}
document.getElementById('btnCheckCardNumber').addEventListener('click', logValidationMessage);
<input type="text" id="cardNumber" />
<input type="button" id="btnCheckCardNumber" value="Check" />
I did figure this out. I created a function as suggested and passed that function as an argument in another function: (which I now know is a callback function)
function creditCardMessageFunction () {
let numberDigit;
let creditCardMessage;
if ($cardNumber.val().length < 13) {
numberDigit = 'Too few digits. ';
} else if ($cardNumber.val().length > 16) {
numberDigit = 'Too many digits. ';
} else {
numberDigit = 'Numeric Values Only. ';
}
creditCardMessage = numberDigit + 'Please enter numbers between 13 and 16.';
return creditCardMessage;
}
I currently have this validation but when pressed numerous times the input sometimes get pass.
Text field ID : service-rate-amount
$('#service-rate-amount').keyup(function() {
var val = $(this).val();
var checkIf50or00cents = new RegExp("^[0-9]+(\.([0,5]{1})?([0]{1})?)?$");
var limitDigits = new RegExp("/^\d{0,3}(\.\d{1,2})?$/");
if(isNaN(val) && val != "."){
showMessageModal("Only numeric characters are accepted");
val = val.replace(/[^0-9\.]/g,'');
if(val.split('.').length>2) {
val = val.replace(/\.+$/,"");
showMessageModal("Only one decimal point is accepted");
}
} else if (!checkIf50or00cents.test(val)){
val = val.slice(0,-1);
showMessageModal("Only 50 cents or 00 cents are allowed");
}
if (!(/^\d{0,3}(\.\d{1,2})?$/.test(val))) {
if(val.length == 4){
if( val.charAt(3) != "."){
val = val.slice(0, -1);
showMessageModal("Only three digits before decimal point is accepted");
}
}
}
$(this).val(val);
});
I want to have a input field that will accept ....
00.50 up to 999.50
I need in increments of .50 centavos, Sorry for my bad english
If you parse the value into a number that can be compared you could remove some of the complexity. see comments below
var dollars = document.querySelector('#dollars');
function checkDollarInput(){
var value = parseFloat( dollars.value ),
valueInt = parseInt( value );
if( dollars.value.match(/[^0-9.-]/) ){
showMessageModal('please use only numbers', value);
return false;
}
// check the max value
if( value > 999.5 ){
showMessageModal('over max value', value);
return false;
}
// check the min value
if( value < 0.5 ){
showMessageModal('under min value', value);
return false;
}
// ensure the correct decimal using modulo division remainer
if( value % valueInt !== 0 && value % valueInt !== .5 ){
showMessageModal('needs to be .0 or .50', value );
return false;
}
console.log( 'success', value );
// all tests have passed
return true;
}
// im only logging value for the sake of testing
function showMessageModal( message, value ){
console.log.apply(console, arguments);
// do something to show the modal
}
<script src="http://codepen.io/synthet1c/pen/WrQapG.js"></script>
I want to have a input field that will accept .... 00.50 up to 999.50
<form id="form">
<input id="dollars" type="text" value="40.50" />
<input id="submit" type="button" value="checkDollarInput" onclick="checkDollarInput()" />
</form>
You could filter away all textual input via the use of input with type number.
HTML
<input id="validate" type="number">
JavaScript
document.getElementById("validate").addEventListener("keyup", function(e) {
var v = Number(this.value);
if(v >= 0.5 && v <= 999.5) {
var decimals = (v % 1).toFixed(2);
if(decimals == 0 || decimals == 0.5) {
console.log("Acceptable");
}
}
}, false);
I want to validate cell number using JavaScript.
Here is my code.
if(number.value == "") {
window.alert("Error: Cell number must not be null.");
number.focus();
return false;
}
if(number.length != 10) {
window.alert("Phone number must be 10 digits.");
number.focus();
return false;
}
Here is the issue, when I submit the form with out entering the phone number, it is showing the error cell number must not be null. it works fine.
When I submit the form with cell number less than 10 digits, it is showing phone number must be 10 digits. It is also fine.
The problem is when I submit the form with 10 digits, then also it is showing the error phone number must be 10 digits.
Please help me.
Thank You.
And also need the validation code for only digits for cell number.
If number is your form element, then its length will be undefined since elements don't have length. You want
if (number.value.length != 10) { ... }
An easier way to do all the validation at once, though, would be with a regex:
var val = number.value
if (/^\d{10}$/.test(val)) {
// value is ok, use it
} else {
alert("Invalid number; must be ten digits")
number.focus()
return false
}
\d means "digit," and {10} means "ten times." The ^ and $ anchor it to the start and end, so something like asdf1234567890asdf does not match.
function IsMobileNumber(txtMobId) {
var mob = /^[1-9]{1}[0-9]{9}$/;
var txtMobile = document.getElementById(txtMobId);
if (mob.test(txtMobile.value) == false) {
alert("Please enter valid mobile number.");
txtMobile.focus();
return false;
}
return true;
}
Calling Validation Mobile Number Function HTML Code -
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
alert("Please enter only Numbers.");
return false;
}
return true;
}
function ValidateNo() {
var phoneNo = document.getElementById('txtPhoneNo');
if (phoneNo.value == "" || phoneNo.value == null) {
alert("Please enter your Mobile No.");
return false;
}
if (phoneNo.value.length < 10 || phoneNo.value.length > 10) {
alert("Mobile No. is not valid, Please Enter 10 Digit Mobile No.");
return false;
}
alert("Success ");
return true;
}
<input id="txtPhoneNo" type="text" onkeypress="return isNumber(event)" />
<input type="button" value="Submit" onclick="ValidateNo();">
If you type:
if { number.value.length!= 10}...
It will sure work because the value is the quantity which will be driven from the object.
This function check the special chars on key press and eliminates the value if it is not a number
function mobilevalid(id) {
var feild = document.getElementById(id);
if (isNaN(feild.value) == false) {
if (feild.value.length == 1) {
if (feild.value < 7) {
feild.value = "";
}
} else if (feild.value.length > 10) {
feild.value = feild.value.substr(0, feild.value.length - 1);
}
if (feild.value.charAt(0) < 7) {
feild.value = "";
}
} else {
feild.value = "";
}
}
Verify this code :
It works on change of phone number field in ms crm 2016 form .
function validatePhoneNumber() {
var mob = Xrm.Page.getAttribute("gen_phone").getValue();
var length = mob.length;
if (length < 10 || length > 10) {
alert("Please Enter 10 Digit Number:");
Xrm.Page.getAttribute("gen_phone").setValue(null);
return true;
}
if (mob > 31 && (mob < 48 || mob > 57)) {} else {
alert("Please Enter 10 Digit Number:");
Xrm.Page.getAttribute("gen_phone").setValue(null);
return true;
}
}
<script type="text/javascript">
function MobileNoValidation()
{
var phno=/^\d{10}$/
if(textMobileNo.value=="")
{
alert("Mobile No Should Not Be Empty");
}
else if(!textMobileNo.value.match(phno))
{
alert("Mobile no must be ten digit");
}
else
{
alert("valid Mobile No");
}
}
</script>
I used the follow code.
var mobileNumber=parseInt(no)
if(!mobileNumber || mobileNumber.toString().length!=10){
Alert("Please provide 10 Digit numeric value")
}
If the mobile number is not a number, it will give NaN value.
<script>
function validate() {
var phone=document.getElementById("phone").value;
if(isNaN(phone))
{
alert("please enter digits only");
}
else if(phone.length!=10)
{
alert("invalid mobile number");
}
else
{
confirm("hello your mobile number is" +" "+phone);
}
</script>