flask:how to stop python programs when jquery find an invalid input? - javascript

Im new to Flask .
I try a user log-in page
I validate the user input by jQuery code:
$(document).ready(function(){
//alert('begin');
$(".input.reg_butn").click(function(){
if($("[name=username]").val()==""){
alert("username empty");
}else{
if($("[name=password]").val()==""){
alert("password empty");
}
}
})
})
and my python code is as follow:
#app.route('/login',methods=['GET','POST'])
def login():
.....
My question is how to stop python code running when the js code finds that the user submitted an invalid value (such as empty username of password).
I use alert in JS to notify the user, BUT the python code run as usual.
How to solve it ?

I don't think this is the right approach: to validate data in on the client side. Instead you should do it on the server side using a flask extension which deals with forms and form validation: flask-WTF.

You are capturing the click of the input button, but you need to stop form submission. If you do this with a handler that listens to that instead, you will also be able to run your checks when the user presses the enter key.
$(document).ready(function() {
// Adjust this selector as necessary.
$("form.login").submit(function() {
$(this).preventDefault();
if ($("[name=username]", this).val() == "") {
alert("username empty");
} else {
if ($("[name=password]", this).val() == "") {
alert("password empty");
}
}
});
If you are using HTML5, though, this can all be simplified by adding required to your input tags.
<input type="text" name="username" required>
Any browser that supports it will trap the form submission for you (without the need for any JavaScript).

Related

How to go to another HTML page, if form is validated and stay in the same page if it is not validated?

So I have a HTML file where I collect some input, and I validate it using JavaScript.
If I give the wrong type of input I get the alert window which I have given. When I press 'ok' in the alert window it goes to the target page instead of staying in the same page. How do I fix this error?
function validate()
{
var x = document.getElementById("zc").value;
if (x.toString().length != 6) {
alert("Enter a valid zip-code which contains 6 digits");
x.focus();
return False;
}
else {
alert("Form Success");
return True;
}
}
My HTML file is given below, I have skipped the parts where I collected input. If it is false shouldn't be in the same page instead of going to welcom.html.
<form action="welcome.html" onsubmit="return validate()">
<button type="submit">Submit</button>
</form>
you could use the window.location.href method. I will leave a link from w3schools where it explains how to redirect to another page.
link: https://www.w3schools.com/howto/howto_js_redirect_webpage.asp

How do I check if image is generated before clicking submit button?

I'm creating a ASP.NET MVC5 application that utilizes jSignature to capture the user's signature. It looks like this, if you're unfamiliar with the plugin:
When the user clicks "Save", an image of their signature is generated and saved in an <img/> right underneath the signature pad:
I want to do some front-end validation to make sure that the user has clicked "save" and, therefore, generated the signature image before submitting the entire form. I'd like to do this with jQuery if possible. I have a pseudo-code mock-up of what I think this code is supposed to look like, but I'm having trouble turning it into real-world use:
$("#entireFormSubmitButton").click(function(){
if($("#imageOfSignature").doesNotExistOnPage){
alert("Your signature is required before submitting this form");
// also block the user from submitting form until signature provided
}
});
I'm having trouble writing this piece of custom front-end validation since ASP.NET has already done most of the work for me to make sure all other required fields are filled out. Can I get some help turning this into working code?
$("#entireFormSubmitButton").click(function(e){
//block the user from submitting and check for signature
e.preventDefault();
if( $("#imageOfSignature").length == 0 ||
$("#imageOfSignature").attr("src") == "" ||
$("#date-of-birth-input").val() == ""){
alert("Your message");
} else {
//all good, an image exists
$(this).closest('form').submit();
}
});

Preventing form submission with invalid fields

I have been trying to make a simple HTML form that takes a phone number, password, and confirmed password. I tried using the HTML5 required attribute to ensure all fields were filled out upon submission, but since finding out Safari doesn't support that, I moved on to using the following code from a different stack overflow topic to validate the form:
var form = document.getElementById('text'); // form has to have ID: <form id="formID">
form.noValidate = true;
form.addEventListener('submit', function (event) { // listen for form submitting
if (!event.target.checkValidity()) {
event.preventDefault(); // dismiss the default functionality
if (document.getElementById('password_confirm').value != document.getElementById('password').value) {
alert('Passwords must match');
//document.getElementById("alert_pw_match").style.color = rgba(37, 33, 90, 0.64);
} else {
// input is valid -- reset the error message
alert('All fields are required');
}
}
}, false);
The issue I'm having is that I want to move away from using the standard alert boxes and just highlight the relevant fields or display some text indicating why the form is invalid, but whenever I add a line other than the alert the form submits without anything happening.

JavaScript Form Validation Query

I've just wrote some validation code so as to check if either of my radio buttons from my web form have been selected before they are submitted. I've just starting learning php as I want to be able to store the value of each radio button in a .csv file.
Because I have my action attribute set to trigger a php script, I get my alert box, but as soon as I click OK after pressing submit the browser goes straight to the php script (inevitably).
Is there a way I can return to my initial index.html after the alert message?
I have not actually written any php as yet, so would this go in the php script or the javascript?
Heres my code so far:
$("#submit").on("click", function() {
var radio = $("input[type=radio][name=emotion]")[0].checked;
var radio2 = $("input[type=radio][name=emotion]")[1].checked;
var radio3 = $("input[type=radio][name=emotion]")[2].checked;
if(!radio && !radio2 && !radio3) {
alert("You must select at least one word!");
}
else {
alert("Please rate the next item!")
}
});
In Jquery you should use .submit() function to validate a form.
Then to avoid to submit the form you can use the function event.preventDefault()
And if you want to go to the index you can use window.location = "yourURL"
You must use form.onsubmit().
For example, if your form's name is myForm:
document.forms['myForm'].onsubmit = function()
{
if (this.elements['emotion'].value)
{
alert("Please rate the next item!");
}
else
{
alert("You must enter at least one word!");
return false;
}
}
And after alert "Please rate the next item!" form will be send.
Actually you can use jquery $.post() , an easy solution is just to post your php page without leaving index page.
http://api.jquery.com/jquery.post/
$.post( "yourpage.php" );
You probably have the input type of the submit button as submit? Set this to button, so the action doesn't take place and only jQuery is executed.
But then you have to submit the form by jQuery when validation was successful:
document.myFormId.submit();

Focus On Password Field If Username Has Value

My request is simple, I have a login form. We have a "save username" option on the login form. When the page loads, if the username input field has value (they have saved their username) I want to Autofocus on the password input instead of the username input.
Below is the jQuery I currently have which is not working:
$(document).ready(function() {
if($('#username').val() != ''){
$('#p').focus();
}
});
Currently nothing happens, there are no console errors and the #username input stays focused or highlighted.
Any ideas on how to focus on an input field so the user can start typing there automatically?
put it out of $(document).ready(), use:
$(window).load(function() {
if($('#username').val() != ''){
$('#p').focus();
}
});
The problem is solved. Thanks plalx for pointing out the timing issue.
I needed to wrap the script in a "set timeout" function. Below is the final working script.
$(document).ready(function() {
if($('#username').val() != ''){
setTimeout(function () {
$('#p').focus();
}, 50);
}
});
You need to specity if user has saved the username or not.
Then you have to see what usernamehas been saved.
Then focus on the password field.
Here is your code
var saveduser="piyush"; //get username from saved fields
$(window).ready(function(){
if(saveduser!="")
{
$("#user").val(saveduser);
$("#pass").focus();
}
});
Here is the fiddle that I have created
http://jsfiddle.net/piyushkmr/86XxN/1/
You can set variable saveduser to username using javascript cookies or php.

Categories