How to check password using RegEx using jquery and without keyup function - html

I want to make a signup form in which user type password which contains combination of alphabet,letter and length > 6 otherwise form will not submit
here I have shown function specifically for password only but i have other function for other input types and they are working properly but it is not.
$('#password').hide();
var password = false;
$('#user_password').focusout(function() {
check_password();
});
function check_password() {
var password = new RegExp(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[^a-zA-Z0-9])(?!.*\s).{8,15}$/);
var password_length = $('#user_password').val().length;
if (password.test($("#user_password").val()) && password_length > 6) {
alert("hello");
$('#password').hide();
} else {
$('#password').html('Password should be more than 6 character and should contain a letter and number');
$('#password').show();
password = true;
}
}
$('#signupfrm').submit(function() {
password = false;
check_password();
if (password == false) {
return true;
} else {
return false;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form role="form" name="signupfrm" id="signupfrm" method="post" action="<?php $_SERVER['PHP_SELF'] ?>">
//other input types above password input type
<input type="password" class="form-control" placeholder="Password..." name="user_password" id="user_password" required="">
<span id="password">
</span>
<button type="submit" class="btn btn-login" name="signup" id="signup" value="Signup">Create My Account</button>
</form>

You likely meant to do this
But you need to fix your regex https://regex101.com/r/ND19JO/1
I suggest this:
^(?=.{6,})(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=]).*$
6 chars one lowerCase, one upperCase and one special char
const passwordRe = new RegExp(/^(?=.{6,})(?=.*[a-z])(?=.*[A-Z])(?=.*[##$%^&+=]).*$/);
const check_password = function() {
const pw = $('#user_password').val();
const pwOK = passwordRe.test(pw);
$('#pwError').toggle(!pwOK);
return pwOK;
}
$(function() {
$('#user_password').focusout(check_password)
$('#signupfrm').on("submit", function(e) {
if (!check_password()) e.preventDefault();
})
})
#pwError {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form role="form" name="signupfrm" id="signupfrm" method="post" action="">
<input type="password" class="form-control" placeholder="Password..." name="user_password" id="user_password" value="bla" required="">
<span id="pwError">Password should be more than 6 character and should contain a letter and number</span>
<button type="submit" class="btn btn-login" name="signup" id="signup" value="Signup">Create My Account</button>
</form>

If you have the correct regex, you don't have to test separately for the length:
var password = /^(?=.*\d)(?=.*[a-zA-Z])(?!.*\s).{7,15}$/;
It seems you also do not allow white space in your password. The way to prevent the form from submitting is to execute event.preventDefault() in your submit handler if the password is invalid. So the function check_password needs to return a flag that will be checked. I have removed the code that hides and unhides the password field to reduce the code to its essence:
function check_password() {
var password = /^(?=.*\d)(?=.*[a-zA-Z])(?!.*\s).{7,15}$/;
if (password.test($("#user_password").val())) {
return true;
}
else {
console.log('Password should be more than 6 character and should contain a letter and number and no spaces');
return false;
}
}
$(function() {
$('#signupfrm').submit(function() {
if (!check_password(event)) {
event.preventDefault();
}
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form role="form" name="signupfrm" id="signupfrm" method="post" action="<?php $_SERVER['PHP_SELF'] ?>">
<input type="password" class="form-control" placeholder="Password..." name="user_password" id="user_password" required="">
<span id="password">
</span>
<button type="submit" class="btn btn-login" name="signup" id="signup" value="Signup">Create My Account</button>
</form>
Note that you should only attempt to create the submit handler once you are sure that the document's elements have been created, i.e. element id signupform in this case. That is why that code is placed in a jQuery.ready() block (or its shortcut version). See .ready().

Related

Bad : jQuery username validation

When I try to let the name are false it should let border color of submit input turn into red but nothing happen in name
Body
<div id="name">
<input type="text" id="inputName" placeholder="Name">
</div>
<input id="signup" type="submit" value="SIGN UP">
Script
function isName(inputName){
var regex = /^[A-Za-z0-9\w]{4,20}*$/;
return regex.test(inputName);
}
$("#signup").click(function ()
{
if (isName($("#inputName").val()) == false)
{
$("#inputName").css("border-color", "#E33100");
}
})
/^[A-Za-z0-9\w]{4,20}*$/
Invalid regular expression .. Nothing to repeat
* is not a valid regex character on its own.
It must be prefixed by something, frequently . as in .* => "." any character, "*" repeated any number of times (including 0).
Before your * you have {4,20} which means limit previous group to between 4 and 20 characters; this is not valid for something to repeat.
Remove the * and your regex works fine.
function isName(inputName) {
var regex = /^[A-Za-z0-9\w]{4,20}$/;
return regex.test(inputName);
}
$("#signup").click(function() {
console.log(isName($("#inputName").val()));
if (isName($("#inputName").val()) == false) {
$("#inputName").css("border-color", "#E33100");
} else {
$("#inputName").css("border-color", "green");
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="name">
<input type="text" id="inputName" placeholder="Name">
</div>
<input id="signup" type="submit" value="SIGN UP">

Which input element that accept digits only and allows a limited number of characters

I am trying to implement an (zip code of my country) input field that only accept digits and limit the number of characters to 5.
Which html input type and attributes are more appropriate for this task ?
<input type="text" name="zipcode" pattern="[0-9]{5}" />
pattern="\d{5}" would also work. But make sure to re-check it in your target-script because form-elements can be manipulated.
A complete example (WITH JQUERY) for checking values on change or keyup in the .checkFieldNum values and on submit the form.
JS
function checkNum(value)
{
return value.match(/\d{5}/);
}
$(document).ready(function(){
// trigger if element-value with class="checkFieldNum" changes or key is pressed
$('.checkFieldNum').on('change keyup',function(event){
if(checkNum($(this).val()) === false)
{
$(this).css({background:'tomato'})
}
else
{
$(this).css({background:''})
}
})
// trigger if form should be submitted
$('.formClassForSubmit').on('submit',function(event){
event.preventDefault();
var goOn = true;
$('.checkFieldNum').each(function(){
if(checkNum($(this).val()) === false)
{
goOn = false;
alert($(this).attr('name') + ' has wrong value')
}
})
if(goOn === true)
{
// In this case, everything is OK and go on whatever you will do..
}
})
})
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="?" method="post" class="formClassForSubmit">
<input type="text" class="checkFieldNum" name="zipcode1" pattern="[0-9]{5}" />
<input type="text" class="checkFieldNum" name="zipcode2" pattern="\d{5}" />
<input type="submit" name="send" value="send" />
</form>
see https://jsfiddle.net/7hbj6a3e/3/
<input type="number" minlength="5" maxlength="5" name="zipcode" />
see https://www.w3schools.com/tags/tag_input.asp

Redirecting to a page after submitting form in HTML

I'm fairly new to coding in HTML. After hours of searching the internet for a way to do this, I failed and so I'm here. I was setting up a CSRF Proof of concept page here, I want it to redirect to another page which will execute the payload that the CSRF had implemented.
<html>
<body>
<form action="https://website.com/action.php?" method="POST">
<input type="hidden" name="fullname" value="john" />
<input type="hidden" name="address" value="street 2, 32 ave" />
<input type="submit" value="Submit request" />
</form>
</body>
</html>
So after this form is submitted using, all it does is redirect to this page
But instead of that, I want it to redirect to another URL as well as submit that form.
For anyone else having the same problem, I figured it out myself.
<html>
<body>
<form target="_blank" action="https://website.com/action.php" method="POST">
<input type="hidden" name="fullname" value="Sam" />
<input type="hidden" name="city" value="Dubai " />
<input onclick="window.location.href = 'https://website.com/my-account';" type="submit" value="Submit request" />
</form>
</body>
</html>
All I had to do was add the target="_blank" attribute to inline on form to open the response in a new page and redirect the other page using onclick on the submit button.
You need to use the jQuery AJAX or XMLHttpRequest() for post the data to the server. After data posting you can redirect your page to another page by window.location.href.
Example:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
window.location.href = 'https://website.com/my-account';
}
};
xhttp.open("POST", "demo_post.asp", true);
xhttp.send();
in case you are generating the form programmatically you can add this script at the end of the form
<script type="text/javascript">document.forms["FormId"].submit();</script>
What you could do is, a validation of the values, for example:
if the value of the input of fullanme is greater than some value length and if the value of the input of address is greater than some value length then redirect to a new page, otherwise shows an error for the input.
// We access to the inputs by their id's
let fullname = document.getElementById("fullname");
let address = document.getElementById("address");
// Error messages
let errorElement = document.getElementById("name_error");
let errorElementAddress = document.getElementById("address_error");
// Form
let contactForm = document.getElementById("form");
// Event listener
contactForm.addEventListener("submit", function (e) {
let messageName = [];
let messageAddress = [];
if (fullname.value === "" || fullname.value === null) {
messageName.push("* This field is required");
}
if (address.value === "" || address.value === null) {
messageAddress.push("* This field is required");
}
// Statement to shows the errors
if (messageName.length || messageAddress.length > 0) {
e.preventDefault();
errorElement.innerText = messageName;
errorElementAddress.innerText = messageAddress;
}
// if the values length is filled and it's greater than 2 then redirect to this page
if (
(fullname.value.length > 2,
address.value.length > 2)
) {
e.preventDefault();
window.location.assign("https://www.google.com");
}
});
.error {
color: #000;
}
.input-container {
display: flex;
flex-direction: column;
margin: 1rem auto;
}
<html>
<body>
<form id="form" method="POST">
<div class="input-container">
<label>Full name:</label>
<input type="text" id="fullname" name="fullname">
<div class="error" id="name_error"></div>
</div>
<div class="input-container">
<label>Address:</label>
<input type="text" id="address" name="address">
<div class="error" id="address_error"></div>
</div>
<button type="submit" id="submit_button" value="Submit request" >Submit</button>
</form>
</body>
</html>
For me this one worked pretty well.
=> form target to blank (opens in a new tab) + input id to be recognized in Javascript + script that redirects.
<html>
<body>
<form target="_blank" action="https://website.com/action.php" method="POST">
<input type="hidden" name="fullname" value="Sam" />
<input type="hidden" name="city" value="Dubai " />
<input type="submit" value="Submit request" id="submitBtn"/>
<script>
document.getElementById("submitBtn").addEventListener("click", myFunction);
function myFunction() {
window.location.href="http://programminghead.com";
}
</script>
</form>
</body>
</html>
I found it here: https://programminghead.com/submit-button-redirect-to-another-page-in-html

Why wont <button type="submit"> work?

I have a standard HTML form, and the button is not working. I know it is directing to the correct page, and as far as I can see everything looks perfect.
It lets me click the button, but then nothing happens, it doesn't direct me to the send.php page or anything.
<form method="post" action="http://www.URL.net/send.php">
<p>
<label for="name">Name <span class="required">*</span></label>
<input type="text" name="name" id="name">
</p>
<p>
<label for="email">Email <span class="required">*</span></label>
<input type="text" name="email" id="email">
</p>
<p>
<label for="subject">Subject</label>
<input type="text" name="subject" id="subject">
</p>
<p>
<label for="subject">Message <span class="required">*</span></label>
<textarea name="message" id="message" cols="45" rows="10"></textarea>
</p>
<div class="fBtn">
<button type="submit" name="submit" id="submit" class="regButton"><i class="icon-paper-plane"></i>Send Message</button>
</div>
</form>
Also, I have tried using <input type="submit" name="submit" id="submit" class="regButton" value="Send Message" /> as well, but it also isn't working for some odd reason.
Tested in Chrome and IE11.
EDIT Here is the JS for form vaildation:
$('#submit').click(function(){
$('input#name').removeClass("errorForm");
$('textarea#message').removeClass("errorForm");
$('input#email').removeClass("errorForm");
var error = false;
var name = $('input#name').val();
if(name == "" || name == " ") {
error = true;
$('input#name').addClass("errorForm");
}
var msg = $('textarea#message').val();
if(msg == "" || msg == " ") {
error = true;
$('textarea#message').addClass("errorForm");
}
var email_compare = /^[a-zA-Z0-9._-]+#[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i;
var email = $('input#email').val();
if (email == "" || email == " ") {
$('input#email').addClass("errorForm");
error = true;
}else if (!email_compare.test(email)) {
$('input#email').addClass("errorForm");
error = true;
}
if(error == true) {
return false;
}
var data_string = $('.contactForm form').serialize();
$.ajax({
type: "POST",
url: $('.contactForm form').attr('action'),
data: data_string,
success: function(message) {
if(message == 'SENDING'){
$('#success').fadeIn('slow');
}
else{
$('#error').fadeIn('slow');
}
}
});
return false;
});
You appear to have some JavaScript that automatically submits every form using AJAX. Since you’re on the domain trishajohnson.net, the same-origin policy prevents JavaScript from opening requests to a (slightly) different domain – www.trishajohnson.net.
There’s an easy fix, though – just use the path part. It’s cleaner anyway.
<form method="POST" action="/tj/send.php">

How to restrict Html5 input to enter single quote and colon

I have created 1 jsp page that contain html form, while submitting html form i have checked input string for not contain any single quote(') or colon(:)
<form action="" method="post" onsubmit="return toValidate('demo')>
<input name="demo" id="demo" />
<input type="submit" value="submit"/>
</form>
Javascript function:
function toValidate(id){
var str = "";
for(var i=0; i<val.length;i++) {
if (val[i] == "'" || val[i] == ":") {
alert(" ' and : not allowed");
return false;
}
else
{
str =str+val[i];
document.getElementById(id).value=str;
}
}
}
My question is that how can i restrict input field using html5 pattern...?
I modified your HTML code with the validation using HTML5 regular expression
<form action="" method="post">
<input name="demo" type="text" id="demo" pattern="[^':]*$" />
<input type="submit" value="submit"/>
</form>
See fiddle here:
http://jsfiddle.net/mzDt9/