How to prevent characters being submitted with form input - javascript

I'm in the process of creating a gambling website, but currently with the betting form input you can type a negative number etc (-100) and you will have 100 coins put into your balance.
I need to restrict the use of anything but number digits being used within the input. Currently my work around is blocking the user from typing in anything other than numbers but you are able to hop into the developer tools and insert the value manually.
I believe i need to have an onSubmit validation for the input which says if anything but numbers are inserted do not allow the submit.
I'm not sure how i will do this, thanks for the help!

put onkeypress="return onKeyValidate(event,alpha);" on your input box,and
call the function
function onKeyValidate(e,charVal){
var keynum;
var keyChars = /[\x00\x08]/;
var validChars = new RegExp(charVal);
if(window.event)
{
keynum = e.keyCode;
}
else if(e.which)
{
keynum = e.which;
}
var keychar = String.fromCharCode(keynum);
if (!validChars.test(keychar) && !keyChars.test(keychar))
{
return false
} else{
return keychar;
}
}

Use ctype_digit()
//returns true
<?php
if (ctype_digit('123')) {
echo 'true';
} else {
echo 'false' ;
}
?>
//returns false
<?php
if (ctype_digit('-123')) {
echo 'true';
} else {
echo 'false' ;
}
?>

you can use this reguler expression to validate for numbers
samp html <button type="submit" onclick="myfunc()">Click Me!</button>
function myfunc(){
var a = /^\d*$/;
{
if(!a.test(value of input))
{
alert('Please provide a Number');
return false;
}
}
}
here
/ at both ends mark the start and end of the regex
^ and $ at the ends is to check the full string than for partial matches
d* looks for multiple occurrences of number charcters
if you want only positive numbers use this/^[+]?([0-9]+(?:[\.][0-9]*)?|\.[0-9]+)$/

this jquery code can solve your problem
$(function(){
$("#submit").click(function(evnt){
var inptTxt = $("#myField").val();
if(check(inptTxt)){
//your test true then submits
$('#form').submit;
}else{ //test failed
evnt.preventDefault();
}
})
})
here the #submit is the id of submit button and #form is the id of the form to be submitted

Related

How can I validate user input (characters and number) with javascript?

From this example
I tried to validate user input when a button was clicked.
$("#check_data").click(function () {
var $userInput = $('#user_input'); //from HTML input box id="user_input"
var pattern = " /*My user input always be like "AB1234567"*/ ";
if ($userInput.val() == '' || !pattern.test($userInput.val())) {
alert('Please enter a valid code.');
return false;
}
});
My user input input always be like "AB1234567" with this exact same characters but different 7 digits number.
I'm new to Javascript and Jquery, if you have any better way to validate user input, please suggest it.
Thank you.
You can use below regex Expression to check
/[A-Za-z0-9]/g
Your code could be like this
var _pattern=/[A-Za-z0-9]/g
if($userInput.val().match(_pattern))
{
//your code goes here..
}
Thanks
You can use the below pattern to check
/^AB\d{7}$/
You can change code to
var pattern = '/^AB\d{7}$/';
if ($userInput.val() == '' || !pattern.test($userInput.val()))
{
alert('Please enter a valid code.');
return false;
}
\d{7} matches 7 digits in the range [0-9]
You can follow below code for this:
if ($userInput.val().match(/[^a-zA-Z0-9 ]/g))
{
// it is a valid value.
} else {
// show error here
}
Hope it helps you.
Try this one.
$("#check_data").click(function(){
var $userInput = $('#user_input').val();
var pattern = /^AB[0-9]{7}?/g;
if(!$userInput.match(pattern)){
alert('Please enter a valid code.');
return false;
}
});

Stop form whitespace when user pressing submit

Okay, so I have a form. Applied a function to it.
All I want to do is when the form is submitted it launches the function, it checks to see if there is white space and throws out a message. I have the following:
function empty() {
var x;
x = document.getElementById("Username").value;
if (x == "") {
alert("Please ensure you fill in the form correctly.");
};
}
<input type='submit' value='Register' onClick='return empty()' />
<input type='text' id="Username" />
This is fine for if someone pressed the space-bar once and enters one line of whitespace, but how do I edit the function so that no matter how many spaces of whitespace are entered with the space-bar it will always throw back the alert.
Thanks in advance. I am very new to JavaScript. So please be gentle.
Trim the string before testing it.
x = document.getElementById("Username").value.trim();
This will remove any whitespace at the beginning and end of the value.
I have made a function for the same, i added another checks (including a regular expresion to detect multiples empty spaces). So here is the code:
function checkEmpty(field){
if (field == "" ||
field == null ||
field == "undefinied"){
return false;
}
else if(/^\s*$/.test(field)){
return false;
}
else{
return true;
}
}
Here is an example working with jquery: https://jsfiddle.net/p87qeL7f/
Here is the example in pure javascript: https://jsfiddle.net/g7oxmhon/
Note: the function checkEmpty still be the same for both
this work for me
$(document).ready(function() {
$('#Description').bind('input', function() {
var c = this.selectionStart,
r = /[^a-z0-9 .]/gi,
v = $(this).val();
if (r.test(v)) {
$(this).val(v.replace(r, ''));
c--;
}
this.setSelectionRange(c, c);
});
});
function checkEmpty(field) { //1Apr2022 new code
if (field == "" ||
field == null ||
field == "undefinied") {
return false;
} else if (/^\s*$/.test(field)) {
return false;
} else {
return true;
}
}

Unable to validate properly in jquery

I'm validating an input from a user in jquery. If the input is empty, false is returned and jquery code doesn't run and if it contains some text the jquery code runs.
Here is an example-
function sendm() {
var valid;
valid = sendmval();
if (valid) {
//jquery code
}
}
function sendmval() {
var valid = true;
if (!$('#message').val()) {
valid = false;
} else {}
return valid;
}
This works fine. However the problem occurs when user inputs blank spaces only and thus results in running of jquery code even on blank input. How can I prevent this ?
Since spaces count as character so you have to use $.trim() of Jquery like below:-
if (!$.trim($('#message').val())) {
valid = false;
}
For more reference:-
https://api.jquery.com/jQuery.trim/
Since space is also a character, simple use .trim() function of Javascript strings to remove blank space in the beginning and end. Then proceed with your check as usual.
Note: I have changed:
if (!$('#message').val())
to
if (!$('#message').val().trim())
See full working code test:
function sendm() {
var valid;
valid = sendmval();
if (valid) {
alert("valid & sendm");
}
}
function sendmval() {
var valid = true;
if (!$('#message').val().trim()) {
valid = false;
} else {}
return valid;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="message">
<button onclick="sendm()">CHECK</button>

JavaScript Form Validation for Textarea with Multiple Values

How would I implement error checking of multiple values entered into a textarea? I need to make sure that the values entered use commas as a delimiter before the form is submitted.
You can use
value.split(",")
to separate each word and individually validate them and
value.split(",").length < 2
to check if commas were entered. Should be good to get you started.
Update: I have update the fiddle with your new inputs. It includes check for empty inputs before or after comma, and it trims out spaces before validation
Working example here
Here is a sample implementation:
Markup
<textarea id="textarea" placeholder="comma separated values"></textarea>
<span id="msg"></span>
<br>
<button onclick="submit()">Submit</button>
Script
function isValid() {
var value = document.getElementById("textarea").value;
var values = value.split(',');
if(values.length > 0 && values.length < 5){
for(var i =0;i<values.length;i++);{
if(parseInt(values[i]) === NaN) return false;
}
return true;
}
return false;
}
function submit(){
if(isValid()){
document.getElementById("msg").innerText = "Valid";
//submit the form
} else {
document.getElementById("msg").innerText = "not a valid input";
}
}

jQuery Use Loop for Validation?

I have rather large form and along with PHP validation (ofc) I would like to use jQuery. I am a novice with jQuery, but after looking around I have some code working well. It is checking the length of a Text Box and will not allow submission if it is under a certain length. If the entry is lower the colour of the text box changes Red.
The problem I have is as the form is so large it is going to take a long time, and a lot of code to validate each and every box. I therefore wondered is there a way I can loop through all my variables rather than creating a function each time.
Here is what I have:
var form = $("#frmReferral");
var companyname = $("#frm_companyName");
var companynameInfo = $("#companyNameInfo");
var hrmanagername = $("#frm_hrManager");
var hrmanagernameInfo = $("#hrManagerInfo");
form.submit(function(){
if(validateCompanyName() & validateHrmanagerName())
return true
else
return false;
});
Validation Functions
function validateCompanyName(){
// NOT valid
if(companyname.val().length < 4){
companyname.removeClass("complete");
companyname.addClass("error");
companynameInfo.text("Too Short. Please Enter Full Company Name.");
companynameInfo.removeClass("complete");
companynameInfo.addClass("error");
return false;
}
//valid
else{
companyname.removeClass("error");
companyname.addClass("complete");
companynameInfo.text("Valid");
companynameInfo.removeClass("error");
companynameInfo.addClass("complete");
return true;
}
}
function validateHrmanagerName(){
// NOT Valid
if(hrmanagername.val().length < 4){
hrmanagername.removeClass("complete");
hrmanagername.addClass("error");
hrmanagernameInfo.text("Too Short. Please Enter Full Name.");
hrmanagernameInfo.removeClass("complete");
hrmanagernameInfo.addClass("error");
return false;
}
//valid
else{
hrmanagername.removeClass("error");
hrmanagername.addClass("complete");
hrmanagernameInfo.text("Valid");
hrmanagernameInfo.removeClass("error");
hrmanagernameInfo.addClass("complete");
return true;
}
}
As you can see for 50+ input boxes this is going to be getting huge. I thought maybe a loop would work but not sure which way to go about it. Possibly Array containing all the variables? Any help would be great.
This is what I would do and is a simplified version of how jQuery validator plugins work.
Instead of selecting individual inputs via id, you append an attribute data-validation in this case to indicate which fields to validate.
<form id='frmReferral'>
<input type='text' name='company_name' data-validation='required' data-min-length='4'>
<input type='text' name='company_info' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager' data-validation='required' data-min-length='4'>
<input type='text' name='hr_manager_info' data-validation='required' data-min-length='4'>
<button type='submit'>Submit</button>
</form>
Then you write a little jQuery plugin to catch the submit event of the form, loop through all the elements selected by $form.find('[data-validation]') and execute a generic pass/fail validation function on them. Here's a quick version of what that plugin might look like:
$.fn.validate = function() {
function pass($input) {
$input.removeClass("error");
$input.addClass("complete");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'complete',
text: 'Valid'
}));
}
function fail($input) {
var formattedFieldName = $input.attr('name').split('_').join(' ');
$input.removeClass("complete");
$input.addClass("error");
$input.next('.error, .complete').remove();
$input.after($('<p>', {
class: 'error',
text: 'Too Short, Please Enter ' + formattedFieldName + '.'
}));
}
function validateRequired($input) {
var minLength = $input.data('min-length') || 1;
return $input.val().length >= minLength;
}
return $(this).each(function(i, form) {
var $form = $(form);
var inputs = $form.find('[data-validation]');
$form.submit(function(e) {
inputs.each(function(i, input) {
var $input = $(input);
var validation = $input.data('validation');
if (validation == 'required') {
if (validateRequired($input)) {
pass($input);
}
else {
fail($input);
e.preventDefault();
}
}
})
});
});
}
Then you call the plugin like:
$(function() {
$('#frmReferral').validate();
});
You could give them all a class for jQuery use through a single selector. Then use your validation function to loop through and handle every case.
$(".validate").each(//do stuff);
form.submit(function(){
if(validateCompanyName() && validateHrmanagerName()) // Its logical AND not bitwise
return true
else
return false;
You can do this.
var x = $("input[name^='test-form']").toArray();
for(var i = 0; i < x.length; i++){
validateCompanyName(x[i]);
validateHrmanagerName(x[i]);
}

Categories

Resources