How can I check that a form field is prefilled correctly using capybara? - forms

I have a field with a proper label that I can fill in with capybara without a problem:
fill_in 'Your name', with: 'John'
I'd like to check the value it has before filling it in and can't figure it out.
If I add after the fill_in the following line:
find_field('Your name').should have_content('John')
That test fails, although the filling just before worked as I've verified by saving the page.
What am I missing?

Another pretty solution would be:
page.should have_field('Your name', with: 'John')
or
expect(page).to have_field('Your name', with: 'John')
respectively.
Also see the reference.
Note: for disabled inputs, you'll need to add the option disabled: true.

You can use an xpath query to check if there's an input element with a particular value (e.g. 'John'):
expect(page).to have_xpath("//input[#value='John']")
See http://www.w3schools.com/xpath/xpath_syntax.asp for more info.
For perhaps a prettier way:
expect(find_field('Your name').value).to eq 'John'
EDIT: Nowadays I'd probably use have_selector
expect(page).to have_selector("input[value='John']")
If you are using the page object pattern(you should be!)
class MyPage < SitePrism::Page
element :my_field, "input#my_id"
def has_secret_value?(value)
my_field.value == value
end
end
my_page = MyPage.new
expect(my_page).to have_secret_value "foo"

If you specifically want to test for a placeholder, use:
page.should have_field("some_field_name", placeholder: "Some Placeholder")
or:
expect(page).to have_field("some_field_name", placeholder: "Some Placeholder")
If you want to test the user-entered value:
page.should have_field("some_field_name", with: "Some Entered Value")

I was wondering how to do something slightly different: I wanted to test whether the field had some value (while making use of Capybara's ability to re-test the matcher until it matches). It turns out that it's possible to use a "filter block" to do this:
expect(page).to have_field("field_name") { |field|
field.value.present?
}

If the field is a hidden one with an id of 'some_field', then you can use
expect(find("input#somefield", :visible => false).value).to eq 'John'

This the easiest way:
expect(page).to have_field("name", with: "your name")
<input type="text" id="name" />

Related

Validating optional fields in react using Zod

Using react-hook-form, and zod within a Next.js project. Trying to get .optional() to work. It works with simple strings. See the schema below.
//works
const FormSchema = z.object({
website: z.string().optional()
});
But it does not work when I add the .url() flag. It only checks for the valid url. If the field is blank, it throws an error. In other words, the field is no longer optional. It accepts a valid url, but not a blank input field. Of course I want it to accept a blank input and a valid url as the only valid inputs.
//not working. the field is no longer optional.
const FormSchema = z.object({
website: z.string().url().optional()
})
Perhaps the problem has to do with the input field returning the wrong data-type when it's blank?
<label className="block">
<span className="block text-white">Website</span>
<input
id="email-input"
type="text"
className={`block border text-lg px-4 py-3 mt-2 border-gray-200 focus:bg-white text-gray-900 focus:ring-purpleLight focus:ring-2 outline-none w-full disabled:bg-gray-100 disabled:text-gray-400 disabled:cursor-not-allowed`}
{...register("website")}
disabled={isSubmitting}
placeholder="Website"
value={undefined}
/>
</label>
{errors.website && (
<p className="mt-1 text-sm text-red-600">
{errors.website.message}
</p>
)}
Perhaps the problem has to do with the input field returning the wrong data-type when it's blank?
I think this is likely your problem, although I'm not familiar with what react-hook-form might be doing to transform the input before handing it to your schema. The empty field will have the empty string '' as a value when it's blank. If you just use zod directly:
z.string().optional().parse(''); // succeeds because '' is a string
// Whereas this will fail because although '' is a string, it does not
// match the url pattern.
z.string().url().optional().parse('');
.optional() allows for the input value to be undefined so for example:
// These will both successfully parse because of `optional`
z.string().optional().parse(undefined);
z.string().url().optional().parse(undefined);
Going out slightly on a limb here, but if you wanted '' to pass you could add a preprocess step where you convert '' to undefined:
const s = z.preprocess(
(arg) => (arg === "" ? undefined : arg),
z.string().url().optional()
);
console.log(s.safeParse("")); // success (data: undefined)
console.log(s.safeParse("test")); // failure (not a url)
console.log(s.safeParse(undefined)); // success (data: undefined)

How to store date in some variable in Cypress

Can anyone help me how to store date from a field to variable. Here is the HTML which I am looking at:
<input id="date" class="input_date" id="XYZ" type="date" value="2019-01-12" on_input="table()">
I tried:
const date1 = Cypress.moment(). get('#id_value')
If the ID's are unique, you could try getting the val into a variable as below. I have used date id in the below code.
note: In the input html tag there two ID's, may be need to confirm with dev team which one to be used here
cy.get('#date').invoke('val').then((val)=>{
const dateValue = val;
console.log("Here is the date:"+dateValue);
})
Although Cypress imports the moment library, there are no built in commands for it that allow chaining, but you can add a custom command to make it easier.
The toMoment() command must be chained off a previous selecting command like cy.get() or cy.contains(). It returns a moment object which you can then use invoke to call all the methods moment provides, and further chain .should() to test the value returned from those methods.
For example,
Spec
Cypress.Commands.add('toMoment', {prevSubject: true}, (element) => {
return Cypress.moment(element[0].value);
});
it('input tests with moment', () => {
cy.visit('./app/moment-with-input.html');
cy.get('input').toMoment()
.invoke('isValid')
.should('eq', true);
cy.get('input').toMoment()
.invoke('format', 'dddd')
.should('eq', 'Saturday');
cy.get('input').toMoment()
.invoke('diff', Date(2020, 2, 5), 'days')
.should('eq', -391);
})
HTML fragment (put in '/app' folder of project)
<input id="date" class="input_date" id="XYZ" type="date" value="2019-01-12" on_input="table()">

Zend_Validate_Date returns true on 2011-02-31

What should i do ?
$edit_end_date = '2011-02-31';
$validator_date = new Zend_Validate_Date(array('format' => 'yyyy-mm-dd'));
$isval = $validator_date->isValid($edit_end_date);
if((!$isval) || empty($edit_end_date))
{
echo "Please Enter Valid End Date. !";
}else{
echo "Entered Is Valid End Date. !";
}
how come it returns true date ?
According to the Zend API Docs, it appears that Zend_Validate_Date will only validate whether the argument passed to it, is a valid date construct (also considers locale), it will not validate if the date actually exists.
Zend_Validate_Date allows you to validate if a given value contains a date. This validator validates also localized input.
-- Edit --
Looks like you can use PHP's built in checkdate() function to determine if a date is valid or not.
There are bugs in data validation (ZF-7583 at issue tracker). Look at Zend_Validate_Date just doesn't work properly
You can use regex validation like in answer to linked question, but it will only check for syntax, not if date exists for real. For this you can use checkdate() - as Mike Purcell suggested - combined with Zend_Validate_Callback:
$validator1 = new Zend_Validate_Regex(
array('pattern' => '/^[0-9]{4}-[0-9]{2}-[0-9]{2}$/')
);
$validator1->setMessage(
"Date does not match the format 'yyyy-mm-dd'",
Zend_Validate_Regex::NOT_MATCH
);
$validator2 = new Zend_Validate_Callback(function($value)) {
// using checkdate() or other function
});

ModX Evolution: pass variable from url to form text field on page load

I need to pass string from url:
../page.html?code=123456
to a form (eform snippet in modx)
just once is page loaded (link with url and parameter)
Thanks for answer...
My solution:
1. create a new snippet called GetCode
<?php
if( !function_exists('eformGetCode') ) {
function eformGetCode(&$fields,&$templates){
global $modx;
$code = strip_tags($_GET['codeID']);
$templates['tpl']=str_replace('[+display_code+]',$code,$templates['tpl']);
return true; } }
return '';
?>
2. Add eform call (and snippet) on webpage:
[!GetCode!]
[!eForm? ... ... &eFormOnBeforeFormParse=`eformGetCode` !]
3. In eform chunk with form code add line:
<input name="code" id="code" value="[+display_code+]" eform="::1:" type="text"/>
5. Now when you put parametr in url like:
..../page.html?code=123456
this should appear in form.
you would do this exactly like you would in php..
$myVar = $_GET['code'];
If you are having issues, take a peek in the modx error logs...
-sean
Solution by KudyKam is better than official solution in MODX docs, in which they use a database. http://wiki.modxcms.com/index.php/Populate_eform_with_dynamic_data

Asp.Net JQuery Validation Custom Rule

i try to customize the rule of the JQuery validation plugin and I'm almost done. The only problem I got is that the function $("<%=txtUserl.UniqueID %>").val() return undefined. How can I get the value of that textbox ?
$("#aspnetForm").validate
(
{
rules:
{
<%=txtUser.UniqueID %>:
{
required: true,
remote: "CheckUser.aspx?User=" + $("#<%=txtUser.ClientID %>").val()
}
},
messages:
{
<%=txtUser.UniqueID %>:
{
remote: "Invalid user"
}
}
}
);
And in my webform
<asp:TextBox ID="txtUser" runat="server" TabIndex="1" />
UPDATE
I change to use ClientID instead of UniqueID. Also, I put my javascript code at the end of my file instead of in the beginning of the file.
Now, the problem I got is txtUser.val() return an empty string "". in fact, I notice that it's return the old value of the textbox if I change the value. It's doesn't return the current value, which is want I need...
try txtUser.ClientID instead of UniqueID
$("#<%=txtUser.ClientID %>").val()
Note the # that's missing as well.
Yes use the txtUser.ClientID but also you have to use the (#) to get the value of the text box your statement should be
$("#"+"<%=txtUser.UniqueID %>").val()
if you don't use (#) sign then it will give error
hope this will help