I use this question "Agree on Terms"-checkbox code to add "Agree on Terms" on my PHP Wordpress Page but i need change error messagge if user not accept the checkbox.
Is possibile?
This is my code use
<form action="#" onsubmit="if(document.getElementById('agree').checked) { return true; } else { alert('Please indicate that you have read and agree to the Terms and Conditions and Privacy Policy'); return false; }">
<input type="checkbox" required name="checkbox" value="check" id="agree" /> I have read and agree to the Terms and Conditions and Privacy Policy
<button type="submit" class="btn" name="reg_user">Register</button>
</form>
Just change this string in your code:
'Please indicate that you have read and agree to the Terms and Conditions and Privacy Policy'
Make sure you don't use ' in your error msg itself - it defines the end of the string.
Edit:
if you remove required name="checkbox" it should work
because if you do have the required name in your code the form itself will check if the checkbox is checked. This would lead to your js code not being executed. Also you should consider puting your js code into a seperate file.
Related
I have the following code in the main.py file. It appears to work in all instances, note when I print out user_details, it prints out the tuple: test,test,test (filled in to the form), so the post request is working. However, somehow, it is not being actually written to the database.
Main nature of error: The insertion is not taking place.
Can someone spot an error in my code?
#ADD COMMENT GET POST REQUEST FUNCTION
#app.route('/add',methods=['GET','POST'])
def addcomment():
if request.method=="GET":
return render_template('addcomment.html')
else:
user_details=(
request.form['title'],
request.form['name'],
request.form['comment']
)
#print(user_details)
insertcomment(user_details)
return render_template('addsuccess.html')
#INSERTING comments into the actual database
def insertcomment(user_details):
connie = sqlite3.connect(db_locale)
c=connie.cursor()
sql_insert_string='INSERT INTO comments (title, name, comment) VALUES (?,?,?)';
c.execute(sql_insert_string,user_details)
connie.commit
connie.close()
print(user_details)
def query_comments():
connie = sqlite3.connect(db_locale)
c=connie.cursor()
c.execute("""
SELECT * FROM comments
""")
userdata=c.fetchall()
return userdata
My suspicion is that there is something wrong with these lines (that is the second function)
insertcomment()
connie = sqlite3.connect(db_locale)
c=connie.cursor()
sql_insert_string='INSERT INTO comments (title, name, comment) VALUES (?,?,?)';
c.execute(sql_insert_string,user_details)
The def addcomment(): function works fine as far as I can see, rendering and returning the right html page on clicking submit.
On the html side, the only thing I can think of that MAY be causing an error is the order of the fields. In the database the fields are Name, Title, Comment (in that order), but in the HTML and the query, they are Title, Name, Comment (in that order specified).
For reference, the HTML file (the form that accepts that data) is below:
<div class="form-group">
<label for="exampleInputEmail1">Title (or catchy caption!)</label>
<input type="text" class="form-control" id="title" name="title" aria-describedby="emailHelp">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Name</label>
<input type="text" class="form-control" id="name" name="name">
</div>
<div class="form-group">
<label for="exampleFormControlTextarea1">Add your amazing answer here:</label>
<textarea class="form-control" id="comment" name="comment" rows="3"></textarea>
</div>
</div>
<div class="form-group">
<button type="submit" class="btn btn-primary">Submit</button>
</form>
On the home page, the data is rendered as follows. I've had to switch the numbers around as you can see, as 2= title 1=name and 3 = comment
{% for user in user_data%}
<tr>
<th scope="row">{{user[0]}}</th>
<td>{{user[2]}}</td>
<td>{{user[1]}}</td>
<td>{{user[3]}}</td>
</tr>
{% endfor %}
Whether the above has anything to do with the error, I don't know (the order)...but I cannot think why.
Finally, here is the table populate .py file. You'll notice there is one extra field - date. Again, could this be a factor?
#populate database file
import sqlite3
db_locale='users.db'
connie=sqlite3.connect(db_locale)
c=connie.cursor() #use this to create commands
#creating a multi-line instruction
c.execute("""
INSERT INTO comments (name,title,comment,date_posted) VALUES
('Ruth Marvin','42','Yeah.Someone was going to say 42','20th July 2050'),
('Jonathan Peter','Meaning?','Surely we need to first define meaning','13th August 2050')
""")
connie.commit()
connie.close()
Can anyone explain why the data is not being POSTED/INSERTED into the database.
The error is in the function insertcomment(). You are missing the brackets with commit:
connie.commit
Just change to:
connie.commit()
which will save the changes to the database. Everything else looks fine including the database query. You are right in using a parameterised query.
sql_insert_string="INSERT INTO comments (title, name, comment) VALUES (%s,%s,%s)"
c.execute(sql_insert_string, user_details)
connie.commit()
this should work. Wrap your db operations into a try, except block to figure out whats wrong with your queries.
try:
sql_insert_string="INSERT INTO comments (title, name, comment) VALUES (%s,%s,%s)"
c.execute(sql_insert_string, user_details)
connie.commit()
except Exception as e:
print(e)
You need to format your SQL insertion string using Python's format() function from the standard library.
Your code:
sql_insert_string='INSERT INTO comments (title, name, comment) VALUES (?,?,?)';
Should be like this:
sql_insert_string='INSERT INTO comments (title, name, comment) VALUES ({}, {}, {})'.format(user_details[0], user_details[1], user_details[2])
Then on your c.execute line just pass sql_insert_string as a parameter. Also, I've found that the flask-sqlalchemy module saves countless headaches, but kudos to you for taking the time to learn SQL and coding it like this.
I'm trying to implement a validation in which i want to disable the button if a specific value entered by user matches the value returned from a service, below is my code:
In the component, i call the service which returns the usernames like below, here is the console log for (UserNames):
0:{Name: "John", userId: "23432"}
1:{Name: "Smith", userId: "12323"}
2:{Name: "Alan", userId: "5223"}
3:{Name: "Jenny", userId: "124"}
in the template, i use NgFor to iterate over the usernames like below
<div *ngFor="let id of UserNames let i = index;">
<input type="radio" name="radio" [checked]="UserNames.userid" (click)="Submit(UserInput)"> <span>Submit</span>
</div>
What i want to achieve is if i enter 23432 the button should disabled because the service already returns userId with this value, unless a new user id entered the button should be enabled.
So the general case of disabling a submit button in the way you're describing would look like:
<button type="submit" [disabled]="someValidationFn()" ...>
and someValidationFn() would, according to the use case you described, contain something like
return UserNames.find(name => { return name.userId === userInput;}));
where userInput is a separate property in the component bound to some user-entered value, presumably via an open text input like
<input name="userInput" [(ngModel)]="userInput" type="text" placeholder="Enter some user id">
But, from the markup snippet you pasted*, I'm not clear that you have that "text" input separate from the radio button group. If the radio button group is meant to have submit actions attached to its individual buttons (it shouldn't), then you're actually guaranteed that the user selection will contain a userId which exists in your UserNames array: the only inputs you're offering are based on the data which came from your service in the first place.
Based on the use case you're describing, I'm not sure why you'd have the radio button group. It sounds like you would just want that text input field with a validation method to make sure that user input does not already exist in the UserNames.
Because I wrote a bunch of abstract snippets there, I thought it might be helpful to show some basic html and js where I put it all together:
// html
<form submit="someSubmitAction()">
<input name="userInput" [(ngModel)]="userInput" type="text" placeholder="Enter some user id">
<button type="submit" [disabled]="someValidationFn()">Submit</button>
</form>
// js
/* don't forget your #Component annotation and class declaration -- I'm assuming these exist and are correct. The class definition encloses all the following logic. */
public userInput: string;
public UserNames: any[];
/* then some service method which grabs the existing UserNames on component's construction or initialization and stores them in UserNames */
public someValidationFn() {
return UserNames.find(name => { return name.userId === userInput;}));
}
public someSubmitAction() {
/* presumably some other service method which POSTs the data */
}
*speaking of the snippet you pasted, there are a couple of errors there:
*ngFor="let id of UserNames <-- you won't get an id by referencing into the UserNames array here; you'll get a member of the UserNames array in each iteration -- i.e., you'd get {Name: "John", userId: "23432"}, then {Name: "Smith", userId: "12323"}, and so on. That's not necessarily an error, but I'm assuming that, b/c you used id as your variable name, you were expecting just the userId field. Otherwise you'd have to use {{id.userId}} in each iteration to access the actual id.
And bob.mazzo mentions another issue with the use of the [checked] attribute
I need to access the input field in the below html. The way the page is setup I need to chain using the 'Address Line 1' text and then sending text to the input field. The input field id changes and so doesn't the layout of the fields depending on user preference. I am struggling. If you need some more information feel free to ask I did not want to overload with too much information.
<td class="labelCol requiredInput">
<label for="00N36000000xina"><span class="assistiveText">*</span>Address Line 1</label>
</td>
<td class="dataCol col02">
<div class="requiredInput">
<div class="requiredBlock"></div>
<input id="00N36000000xina" maxlength="255" name="00N36000000xina" size="20" tabindex="4" type="text">
</div>
</td>
I have accessed like this:
element(by.css('div.pbSubsection:nth-child(3) > table:nth-child(1) > tbody:nth-child(1) > tr:nth-child(2) > td:nth-child(2) > input'))
However depending on where the user puts the fields it can move around. So what I was hoping was to be able to access the label\ and use that to pinpoint its input field.
I don't know protractor but I cobbled together some code that hopefully will work or be close and I'll give you the thought process and some info and hopefully you can use it to fix my code, if needed, and solve the problem.
Start by finding an element by XPath, "//label[text()='Address Line 1']". This searches for a LABEL tag that contains "Address Line 1". Once you find that element, get the label attribute. From your HTML, this label is the id for the INPUT element you want. Now use the id to find the element and do with it what you want.
id = element(by.xpath("//label[text()='Address Line 1']")).getAttribute("label")
input = element(by.id(id))
input.sendkeys("some text")
Haven't tested this myself, but you could try something like this:
// $ is shorthand for element(by.css())
$('div.assistiveText').getAttribute('for').then(function (val) {
// locate the <input> by the value of the attribute on <label>
element(by.id(val)).sendKeys('abc'); // replace sendKeys with your intended function
});
Or if that first locator on the label isn't specific enough, swap out $('div.assistiveText') for element(by.cssContainingText('Address Line 1'))
I tried it for other attributes (I don't have a for attribute anywhere in my app) and it seemed to work for me.
Try this:
List<WebElement> elementList = driver.findElements(By.cssSelector("tbody > tr"));
for (WebElement element : elementList) {
if(element.findElement(By.cssSelector("td.labelCol > label")).getText().equalsIgnoreCase("Address Line 1")) {
element.findElement(By.cssSelector("input[type='text']")).sendKeys("textToInput");
}
}
I'm trying to create my own validation for password confirm, and putting my error on $error. this is my code:
html:
<input ng-model="user.password2" type="password" name="password2" required
ng-keyup="confirmPassword(user.password, user.password2)">
<div ng-messages="register.password2.$error" ng-if="register.password2.$dirty">
<div ng-message="required">Password is required</div>
<div ng-message="passwordsDontMatch">Passwords don't match</div>
</div>
JS:
$scope.confirmPassword = function (pass1, pass2) {
if (angular.isUndefined(pass1) || angular.isUndefined(pass2) || pass1.trim() != pass2.trim()) {
$scope.register.password2.$error["passwordsDontMatch"] = true;
} else {
delete $scope.register.password2.$error["passwordsDontMatch"];
}
console.log($scope.register.password2.$error);
};
it looks like it's working. when the passwords are the same, the message is not displayed and indeed the $error object is empty. But the input is still invalid: ($scope.register.password2.$invalid == true)
you can see what I'm talking about in this plunkr: http://plnkr.co/edit/ETuVqsdSaEBWARvlt4RR?p=preview
try 2 identical passwords. the message will disappear but when you blur from the input, it's still red because internally it's $invalid
The problem probably comes from the fact that you're not typing a password in the first field that matches your regex pattern. The first password is thus undefined, since it doesn't respect the ng-pattern validation rule.
That said, you shouldn't modify the $error array directly. Instead, you should set the validity of the field using $setValidity(). That will not only set and remove the error automatically, but also deal with the $invalid/$valid properties, add and remove the CSS classes, etc.
var valid = !((angular.isUndefined(pass1) || angular.isUndefined(pass2) || pass1.trim() != pass2.trim()));
$scope.register.password2.$setValidity("passwordsDontMatch", valid);
Here's a working example. But remember to enter a valid password in the first place.
Also, instead of implementing this check with ng-keyup, you should make it a directive, which would add a validator to the validators of the form input. This would make sure the check is made whatever the way the second password is entered (i.e. via copy/paste using the mouse only, or simply by prepopulating the form programmatically.
I'm trying to implement a form validation using only the view - i'm trying to avoid creating a new directive for this.
Question - is possible to validate matching password only using the partial/view e.g:
div(ng-class="{true: 'no-match'}[password != password2]")
any tip will be gladly appreciated :)
Yes it is possible ,
<input name="password" ng-class = "{valid: (password1 == password2),
invalid: (password1 != password2) }" ng-pattern="/[0-9]/">
where, valid and invalid are css classes,
to display an error message regarding that, use
<div id="invalidEmail" class="mismatch"
ng-show="testForm.password.$error.pattern && !testForm.password.$pristine">
Please enter atleast a number
</div>
where testForm is your form name like
<form name="testForm"> </form>
For more reference you can see the link http://www.ng-newsletter.com/posts/validations.html